From fc5262f36e50f96626e159c491443f1f81f816bc Mon Sep 17 00:00:00 2001 From: Srinath Narayanan Date: Wed, 8 May 2019 15:48:33 -0700 Subject: [PATCH 001/147] 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 002/147] 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 003/147] 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 ab091c2edf5f320a586f71cda3f5e533a7862a96 Mon Sep 17 00:00:00 2001 From: Dan Schulte Date: Fri, 24 May 2019 11:27:29 -0700 Subject: [PATCH 004/147] Add regenerate-manager and fluent to swagger_to_sdk_config.json autorest options --- swagger_to_sdk_config.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/swagger_to_sdk_config.json b/swagger_to_sdk_config.json index d2bc472803309..8fdc6a8536b3c 100644 --- a/swagger_to_sdk_config.json +++ b/swagger_to_sdk_config.json @@ -5,7 +5,9 @@ "verbose": "", "sdkrel:azure-libraries-for-java-folder": ".", "multiapi": "", - "use": "@microsoft.azure/autorest.java@2.1.85" + "use": "@microsoft.azure/autorest.java", + "regenerate-manager": "", + "fluent": "" }, "version": "0.2.0" } From b544717d7a2289280fe1cd5733beb1e71fb875eb Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Wed, 29 May 2019 09:33:45 -0700 Subject: [PATCH 005/147] 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 006/147] 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 007/147] 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 008/147] 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 009/147] 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 010/147] 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 011/147] 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 012/147] 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 013/147] 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 014/147] 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 015/147] 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 016/147] 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 017/147] 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 018/147] 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 019/147] 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 020/147] 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 021/147] 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 022/147] 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 023/147] 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 024/147] 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 025/147] 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 026/147] 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 027/147] 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 028/147] 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 029/147] 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 030/147] 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 031/147] 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 032/147] 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 033/147] 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 034/147] 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 035/147] 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 036/147] 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 037/147] 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 038/147] 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 039/147] 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 040/147] 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 041/147] 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 042/147] 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 043/147] 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 044/147] 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 045/147] 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 046/147] 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 047/147] 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 048/147] 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 049/147] 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 050/147] 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 051/147] 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 052/147] 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 053/147] 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 054/147] 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 055/147] 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 056/147] 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 057/147] 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 058/147] 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 059/147] 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 9305592d7e6f6896dde24511e3cd5bfe98b22361 Mon Sep 17 00:00:00 2001 From: Shawn Fang <45607042+mssfang@users.noreply.github.com> Date: Mon, 1 Jul 2019 15:53:28 -0700 Subject: [PATCH 060/147] Add samples link (#4206) add sample link to README --- eventhubs/client/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/eventhubs/client/README.md b/eventhubs/client/README.md index 436cc035e11f8..81eebaa7958f7 100644 --- a/eventhubs/client/README.md +++ b/eventhubs/client/README.md @@ -17,7 +17,7 @@ The Azure Event Hubs client library allows for publishing and consuming of Azure the transformed events to a new stream for consumers to observe. [Source code][source_code] | [API reference documentation][api_documentation] | [Product -documentation][event_hubs_product_docs] +documentation][event_hubs_product_docs] | [Samples][sample_examples] ## Getting started @@ -314,6 +314,7 @@ Guidelines](./CONTRIBUTING.md) for more information. [oasis_amqp_v1_error]: http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html#type-error [oasis_amqp_v1]: http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-overview-v1.0-os.html [qpid_proton_j_apache]: http://qpid.apache.org/proton/ +[sample_examples]: ./azure-eventhubs/src/samples/java [sample_consume_event]: ./azure-eventhubs/src/samples/java/ConsumeEvent.java [sample_get_event_hubs_metadata]: ./azure-eventhubs/src/samples/java/GetEventHubMetadata.java [sample_publish_custom_meta_data]: ./azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java @@ -321,4 +322,4 @@ Guidelines](./CONTRIBUTING.md) for more information. [sample_publish_partition_ID]: ./azure-eventhubs/src/samples/java/PublishEventsToSpecificPartition.java [sample_publish_partition_key]: ./azure-eventhubs/src/samples/java/PublishEventsWithPartitionKey.java [sample_sequence_number]: ./azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java -[source_code]: https://github.com/Azure/azure-sdk-for-java/tree/master/eventhubs/client/ \ No newline at end of file +[source_code]: https://github.com/Azure/azure-sdk-for-java/tree/master/eventhubs/client/ From 2f0b3190eef0b4895221c437670f8b58c00302ee Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Tue, 2 Jul 2019 10:00:22 -0700 Subject: [PATCH 061/147] Move KeyVault track 1 libraries to SDK. (#4094) * Move the track 1 keyvault libraries into the SDK folder. Still work that needs to be done to make sure that Track 2 can coexist when it moves in. --- eng/.docsettings.yml | 12 ++++++------ pom.data.xml | 2 +- {keyvault/data-plane => sdk/keyvault}/.gitignore | 0 {keyvault/data-plane => sdk/keyvault}/LICENSE | 0 {keyvault/data-plane => sdk/keyvault}/README.md | 0 .../data-plane => sdk/keyvault}/REGENERATING.md | 0 {keyvault/data-plane => sdk/keyvault}/history.md | 0 .../microsoft-azure-keyvault-complete}/pom.xml | 0 .../keyvault/microsoft-azure-keyvault-core}/pom.xml | 0 .../com/microsoft/azure/keyvault/core/IKey.java | 0 .../microsoft/azure/keyvault/core/IKeyResolver.java | 0 .../microsoft/azure/keyvault/core/package-info.java | 0 .../microsoft-azure-keyvault-cryptography}/pom.xml | 0 .../azure/keyvault/cryptography/Algorithm.java | 0 .../keyvault/cryptography/AlgorithmResolver.java | 0 .../cryptography/AsymmetricEncryptionAlgorithm.java | 0 .../cryptography/AsymmetricSignatureAlgorithm.java | 0 .../azure/keyvault/cryptography/ByteExtensions.java | 0 .../azure/keyvault/cryptography/EcKey.java | 0 .../keyvault/cryptography/EncryptionAlgorithm.java | 0 .../cryptography/IAuthenticatedCryptoTransform.java | 0 .../keyvault/cryptography/ICryptoTransform.java | 0 .../keyvault/cryptography/ISignatureTransform.java | 0 .../keyvault/cryptography/KeyWrapAlgorithm.java | 0 .../azure/keyvault/cryptography/RsaKey.java | 0 .../keyvault/cryptography/SignatureAlgorithm.java | 0 .../keyvault/cryptography/SignatureEncoding.java | 0 .../azure/keyvault/cryptography/Strings.java | 0 .../cryptography/SymmetricEncryptionAlgorithm.java | 0 .../azure/keyvault/cryptography/SymmetricKey.java | 0 .../keyvault/cryptography/algorithms/Aes128Cbc.java | 0 .../algorithms/Aes128CbcHmacSha256.java | 0 .../keyvault/cryptography/algorithms/Aes192Cbc.java | 0 .../algorithms/Aes192CbcHmacSha384.java | 0 .../keyvault/cryptography/algorithms/Aes256Cbc.java | 0 .../algorithms/Aes256CbcHmacSha512.java | 0 .../keyvault/cryptography/algorithms/AesCbc.java | 0 .../cryptography/algorithms/AesCbcHmacSha2.java | 0 .../keyvault/cryptography/algorithms/AesKw.java | 0 .../keyvault/cryptography/algorithms/AesKw128.java | 0 .../keyvault/cryptography/algorithms/AesKw192.java | 0 .../keyvault/cryptography/algorithms/AesKw256.java | 0 .../keyvault/cryptography/algorithms/Ecdsa.java | 0 .../keyvault/cryptography/algorithms/Es256.java | 0 .../keyvault/cryptography/algorithms/Es256k.java | 0 .../keyvault/cryptography/algorithms/Es384.java | 0 .../keyvault/cryptography/algorithms/Es512.java | 0 .../keyvault/cryptography/algorithms/Rs256.java | 0 .../keyvault/cryptography/algorithms/Rsa15.java | 0 .../cryptography/algorithms/RsaEncryption.java | 0 .../keyvault/cryptography/algorithms/RsaOaep.java | 0 .../cryptography/algorithms/RsaSignature.java | 0 .../cryptography/algorithms/package-info.java | 0 .../azure/keyvault/cryptography/package-info.java | 0 .../cryptography/test/AesCbcBCProviderTest.java | 0 .../test/AesCbcHmacShaBCProviderTest.java | 0 .../cryptography/test/AesCbcHmacShaTest.java | 0 .../keyvault/cryptography/test/AesCbcTest.java | 0 .../cryptography/test/AesKwBCProviderTest.java | 0 .../azure/keyvault/cryptography/test/AesKwTest.java | 0 .../cryptography/test/ECKeyBCProviderTest.java | 0 .../azure/keyvault/cryptography/test/ECKeyTest.java | 0 .../azure/keyvault/cryptography/test/PemFile.java | 0 .../cryptography/test/RsaKeyBCProviderTest.java | 0 .../keyvault/cryptography/test/RsaKeyTest.java | 0 .../test/SymmetricKeyBCProviderTest.java | 0 .../cryptography/test/SymmetricKeyTest.java | 0 .../src/test/resources/SECP256key.pem | 0 .../src/test/resources/byte_array.bin | Bin .../src/test/resources/p256key.pem | 0 .../src/test/resources/p256keynew.pem | 0 .../src/test/resources/p256keypubnew.pem | 0 .../src/test/resources/p256sig.der | Bin .../src/test/resources/p384keynew.pem | 0 .../src/test/resources/p384keypubnew.pem | 0 .../src/test/resources/p384sig.der | Bin .../src/test/resources/p521keynew.pem | 0 .../src/test/resources/p521keypubnew.pem | 0 .../src/test/resources/p521sig.der | Bin .../src/test/resources/secp256keynew.pem | 0 .../src/test/resources/secp256keypubnew.pem | 0 .../src/test/resources/secp256sig.der | Bin .../microsoft-azure-keyvault-extensions}/pom.xml | 0 .../keyvault/extensions/AggregateKeyResolver.java | 0 .../keyvault/extensions/CachingKeyResolver.java | 0 .../azure/keyvault/extensions/KeyVaultKey.java | 0 .../keyvault/extensions/KeyVaultKeyResolver.java | 0 .../azure/keyvault/extensions/Strings.java | 0 .../azure/keyvault/extensions/package.html | 0 .../extensions/test/CachingKeyResolverTest.java | 0 .../test/KeyVaultClientIntegrationTestBase.java | 0 .../test/KeyVaultKeyResolverBCProviderTest.java | 0 .../KeyVaultKeyResolverDefaultProviderTest.java | 0 .../keyKeyVaultKeyResolverBCProviderTest.json | 0 .../keyKeyVaultKeyResolverDefaultProviderTest.json | 0 ...t128Base64KeyVaultKeyResolverBCProviderTest.json | 0 ...ase64KeyVaultKeyResolverDefaultProviderTest.json | 0 ...t192Base64KeyVaultKeyResolverBCProviderTest.json | 0 ...ase64KeyVaultKeyResolverDefaultProviderTest.json | 0 ...t256Base64KeyVaultKeyResolverBCProviderTest.json | 0 ...ase64KeyVaultKeyResolverDefaultProviderTest.json | 0 .../keyvault/microsoft-azure-keyvault-test}/pom.xml | 0 .../azure/keyvault/test/EcKeyIntegrationTests.java | 0 .../microsoft-azure-keyvault-webkey}/pom.xml | 0 .../keyvault/webkey/Base64UrlJsonDeserializer.java | 0 .../keyvault/webkey/Base64UrlJsonSerializer.java | 0 .../azure/keyvault/webkey/ByteExtensions.java | 0 .../microsoft/azure/keyvault/webkey/JsonWebKey.java | 0 .../azure/keyvault/webkey/JsonWebKeyCurveName.java | 0 .../webkey/JsonWebKeyEncryptionAlgorithm.java | 0 .../azure/keyvault/webkey/JsonWebKeyOperation.java | 0 .../webkey/JsonWebKeySignatureAlgorithm.java | 0 .../azure/keyvault/webkey/JsonWebKeyType.java | 0 .../azure/keyvault/webkey/package-info.java | 0 .../keyvault/webkey/test/AesValidationTests.java | 0 .../keyvault/webkey/test/ClearMemoryTests.java | 0 .../keyvault/webkey/test/EcHsmValidationTests.java | 0 .../keyvault/webkey/test/EcValidationTests.java | 0 .../keyvault/webkey/test/RsaHsmValidationTests.java | 0 .../keyvault/webkey/test/RsaValidationTests.java | 0 .../keyvault/microsoft-azure-keyvault}/pom.xml | 0 .../azure/keyvault/CertificateIdentifier.java | 0 .../keyvault/CertificateOperationIdentifier.java | 0 .../microsoft/azure/keyvault/IssuerIdentifier.java | 0 .../com/microsoft/azure/keyvault/KeyIdentifier.java | 0 .../microsoft/azure/keyvault/KeyVaultClient.java | 0 .../azure/keyvault/KeyVaultClientBase.java | 0 .../azure/keyvault/KeyVaultClientCustom.java | 0 .../azure/keyvault/KeyVaultClientImpl.java | 0 .../microsoft/azure/keyvault/ObjectIdentifier.java | 0 .../microsoft/azure/keyvault/SecretIdentifier.java | 0 .../authentication/AuthenticationResult.java | 0 .../keyvault/authentication/ChallengeCache.java | 0 .../authentication/KeyVaultCredentials.java | 0 .../azure/keyvault/authentication/package-info.java | 0 .../implementation/KeyVaultClientBaseImpl.java | 0 .../implementation/KeyVaultClientCustomImpl.java | 0 .../azure/keyvault/implementation/package-info.java | 0 .../messagesecurity/HttpMessageSecurity.java | 0 .../azure/keyvault/messagesecurity/JWEHeader.java | 0 .../azure/keyvault/messagesecurity/JWEObject.java | 0 .../azure/keyvault/messagesecurity/JWSHeader.java | 0 .../azure/keyvault/messagesecurity/JWSObject.java | 0 .../messagesecurity/MessageSecurityHelper.java | 0 .../keyvault/messagesecurity/package-info.java | 0 .../com/microsoft/azure/keyvault/models/Action.java | 0 .../microsoft/azure/keyvault/models/ActionType.java | 0 .../azure/keyvault/models/AdministratorDetails.java | 0 .../microsoft/azure/keyvault/models/Attributes.java | 0 .../keyvault/models/BackupCertificateResult.java | 0 .../azure/keyvault/models/BackupKeyResult.java | 0 .../azure/keyvault/models/BackupSecretResult.java | 0 .../azure/keyvault/models/BackupStorageResult.java | 0 .../keyvault/models/CertificateAttributes.java | 0 .../azure/keyvault/models/CertificateBundle.java | 0 .../models/CertificateCreateParameters.java | 0 .../models/CertificateImportParameters.java | 0 .../keyvault/models/CertificateIssuerItem.java | 0 .../models/CertificateIssuerSetParameters.java | 0 .../models/CertificateIssuerUpdateParameters.java | 0 .../azure/keyvault/models/CertificateItem.java | 0 .../keyvault/models/CertificateMergeParameters.java | 0 .../azure/keyvault/models/CertificateOperation.java | 0 .../models/CertificateOperationUpdateParameter.java | 0 .../azure/keyvault/models/CertificatePolicy.java | 0 .../models/CertificateRestoreParameters.java | 0 .../models/CertificateUpdateParameters.java | 0 .../microsoft/azure/keyvault/models/Contact.java | 0 .../microsoft/azure/keyvault/models/Contacts.java | 0 .../keyvault/models/DeletedCertificateBundle.java | 0 .../keyvault/models/DeletedCertificateItem.java | 0 .../azure/keyvault/models/DeletedKeyBundle.java | 0 .../azure/keyvault/models/DeletedKeyItem.java | 0 .../keyvault/models/DeletedSasDefinitionBundle.java | 0 .../keyvault/models/DeletedSasDefinitionItem.java | 0 .../azure/keyvault/models/DeletedSecretBundle.java | 0 .../azure/keyvault/models/DeletedSecretItem.java | 0 .../keyvault/models/DeletedStorageAccountItem.java | 0 .../azure/keyvault/models/DeletedStorageBundle.java | 0 .../keyvault/models/DeletionRecoveryLevel.java | 0 .../com/microsoft/azure/keyvault/models/Error.java | 0 .../azure/keyvault/models/IssuerAttributes.java | 0 .../azure/keyvault/models/IssuerBundle.java | 0 .../azure/keyvault/models/IssuerCredentials.java | 0 .../azure/keyvault/models/IssuerParameters.java | 0 .../azure/keyvault/models/JsonWebKeyCurveName.java | 0 .../azure/keyvault/models/KeyAttributes.java | 0 .../microsoft/azure/keyvault/models/KeyBundle.java | 0 .../azure/keyvault/models/KeyCreateParameters.java | 0 .../azure/keyvault/models/KeyImportParameters.java | 0 .../microsoft/azure/keyvault/models/KeyItem.java | 0 .../azure/keyvault/models/KeyOperationResult.java | 0 .../keyvault/models/KeyOperationsParameters.java | 0 .../azure/keyvault/models/KeyProperties.java | 0 .../azure/keyvault/models/KeyRestoreParameters.java | 0 .../azure/keyvault/models/KeySignParameters.java | 0 .../azure/keyvault/models/KeyUpdateParameters.java | 0 .../azure/keyvault/models/KeyUsageType.java | 0 .../azure/keyvault/models/KeyVaultError.java | 0 .../keyvault/models/KeyVaultErrorException.java | 0 .../azure/keyvault/models/KeyVerifyParameters.java | 0 .../azure/keyvault/models/KeyVerifyResult.java | 0 .../azure/keyvault/models/LifetimeAction.java | 0 .../azure/keyvault/models/OrganizationDetails.java | 0 .../microsoft/azure/keyvault/models/PageImpl.java | 0 .../PendingCertificateSigningRequestResult.java | 0 .../keyvault/models/SasDefinitionAttributes.java | 0 .../azure/keyvault/models/SasDefinitionBundle.java | 0 .../models/SasDefinitionCreateParameters.java | 0 .../azure/keyvault/models/SasDefinitionItem.java | 0 .../models/SasDefinitionUpdateParameters.java | 0 .../azure/keyvault/models/SasTokenType.java | 0 .../azure/keyvault/models/SecretAttributes.java | 0 .../azure/keyvault/models/SecretBundle.java | 0 .../microsoft/azure/keyvault/models/SecretItem.java | 0 .../azure/keyvault/models/SecretProperties.java | 0 .../keyvault/models/SecretRestoreParameters.java | 0 .../azure/keyvault/models/SecretSetParameters.java | 0 .../keyvault/models/SecretUpdateParameters.java | 0 .../keyvault/models/StorageAccountAttributes.java | 0 .../models/StorageAccountCreateParameters.java | 0 .../azure/keyvault/models/StorageAccountItem.java | 0 .../StorageAccountRegenerteKeyParameters.java | 0 .../models/StorageAccountUpdateParameters.java | 0 .../azure/keyvault/models/StorageBundle.java | 0 .../keyvault/models/StorageRestoreParameters.java | 0 .../keyvault/models/SubjectAlternativeNames.java | 0 .../microsoft/azure/keyvault/models/Trigger.java | 0 .../keyvault/models/X509CertificateProperties.java | 0 .../keyvault/models/custom/CertificateBundle.java | 0 .../models/custom/CertificateOperation.java | 0 .../azure/keyvault/models/custom/IssuerBundle.java | 0 .../azure/keyvault/models/custom/KeyBundle.java | 0 .../azure/keyvault/models/custom/SecretBundle.java | 0 .../azure/keyvault/models/custom/package-info.java | 0 .../azure/keyvault/models/package-info.java | 0 .../com/microsoft/azure/keyvault/package-info.java | 0 .../keyvault/requests/CreateCertificateRequest.java | 0 .../azure/keyvault/requests/CreateKeyRequest.java | 0 .../keyvault/requests/ImportCertificateRequest.java | 0 .../azure/keyvault/requests/ImportKeyRequest.java | 0 .../keyvault/requests/MergeCertificateRequest.java | 0 .../requests/SetCertificateIssuerRequest.java | 0 .../azure/keyvault/requests/SetSecretRequest.java | 0 .../requests/UpdateCertificateIssuerRequest.java | 0 .../requests/UpdateCertificateOperationRequest.java | 0 .../requests/UpdateCertificatePolicyRequest.java | 0 .../keyvault/requests/UpdateCertificateRequest.java | 0 .../azure/keyvault/requests/UpdateKeyRequest.java | 0 .../keyvault/requests/UpdateSecretRequest.java | 0 .../azure/keyvault/requests/package-info.java | 0 .../azure/keyvault/test/AsyncOperationsTest.java | 0 .../keyvault/test/CertificateOperationsTest.java | 0 .../azure/keyvault/test/EnhancedKeyVaultTest.java | 0 .../keyvault/test/ITManagedStorageAccountKey.java | 0 .../azure/keyvault/test/KeyOperationsTest.java | 0 .../test/KeyVaultClientIntegrationTestBase.java | 0 .../azure/keyvault/test/SecretOperationsTest.java | 0 .../microsoft/azure/keyvault/test/crudNames.json | 0 .../test/resources/MockUserTokenCredentials.java | 0 .../com/microsoft/azure/keyvault/test/sasNames.json | 0 .../backupRestoreForKeyOperationsTest.json | 0 .../certificateAsyncForAsyncOperationsTest.json | 0 ...estCancellationForCertificateOperationsTest.json | 0 ...tificateContactsAsyncForAsyncOperationsTest.json | 0 ...rtificateUpdateForCertificateOperationsTest.json | 0 ...sCrudOperationsForCertificateOperationsTest.json | 0 ...eCertificatePemForCertificateOperationsTest.json | 0 ...rtificatePkcs12ForCertificateOperationsTest.json | 0 .../createCsrForCertificateOperationsTest.json | 0 ...dCertificatePemForCertificateOperationsTest.json | 0 ...rtificatePkcs12ForCertificateOperationsTest.json | 0 .../crudOperationsForKeyOperationsTest.json | 0 .../crudOperationsForSecretOperationsTest.json | 0 ...zeWithExtraFieldTestForSecretOperationsTest.json | 0 .../disabledSecretGetForSecretOperationsTest.json | 0 ...ncryptDecryptOperationsForKeyOperationsTest.json | 0 ...rtificatePkcs12ForCertificateOperationsTest.json | 0 .../importKeyOperationForKeyOperationsTest.json | 0 .../issuerAsyncForAsyncOperationsTest.json | 0 ...rCrudOperationsForCertificateOperationsTest.json | 0 .../keyAsyncForAsyncOperationsTest.json | 0 ...ificateVersionsForCertificateOperationsTest.json | 0 ...istCertificatesForCertificateOperationsTest.json | 0 .../listKeyVersionsForKeyOperationsTest.json | 0 .../listKeysForKeyOperationsTest.json | 0 .../listSecretVersionsForSecretOperationsTest.json | 0 .../listSecretsForSecretOperationsTest.json | 0 .../secretAsyncForAsyncOperationsTest.json | 0 .../signVerifyOperationsForKeyOperationsTest.json | 0 ...stCrudOperationsForManagedStorageAccountKey.json | 0 ...GetSasDefinitionForManagedStorageAccountKey.json | 0 ...ansparentAuthenticationForKeyOperationsTest.json | 0 ...parentAuthenticationForSecretOperationsTest.json | 0 .../wrapUnwrapOperationsForKeyOperationsTest.json | 0 sdk/keyvault/pom.service.xml | 5 +++++ {keyvault/data-plane => sdk/keyvault}/pom.xml | 12 ++++++------ .../keyvault}/regenerate_and_fix_sdk.py | 0 {keyvault/data-plane => sdk/keyvault}/tests.yml | 0 299 files changed, 18 insertions(+), 13 deletions(-) rename {keyvault/data-plane => sdk/keyvault}/.gitignore (100%) rename {keyvault/data-plane => sdk/keyvault}/LICENSE (100%) rename {keyvault/data-plane => sdk/keyvault}/README.md (100%) rename {keyvault/data-plane => sdk/keyvault}/REGENERATING.md (100%) rename {keyvault/data-plane => sdk/keyvault}/history.md (100%) rename {keyvault/data-plane/azure-keyvault-complete => sdk/keyvault/microsoft-azure-keyvault-complete}/pom.xml (100%) rename {keyvault/data-plane/azure-keyvault-core => sdk/keyvault/microsoft-azure-keyvault-core}/pom.xml (100%) rename {keyvault/data-plane/azure-keyvault-core => sdk/keyvault/microsoft-azure-keyvault-core}/src/main/java/com/microsoft/azure/keyvault/core/IKey.java (100%) rename {keyvault/data-plane/azure-keyvault-core => sdk/keyvault/microsoft-azure-keyvault-core}/src/main/java/com/microsoft/azure/keyvault/core/IKeyResolver.java (100%) rename {keyvault/data-plane/azure-keyvault-core => sdk/keyvault/microsoft-azure-keyvault-core}/src/main/java/com/microsoft/azure/keyvault/core/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/pom.xml (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/EcKey.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureEncoding.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Ecdsa.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256k.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es384.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es512.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyBCProviderTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/PemFile.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/SECP256key.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/byte_array.bin (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p256key.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p256keynew.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p256keypubnew.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p256sig.der (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p384keynew.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p384keypubnew.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p384sig.der (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p521keynew.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p521keypubnew.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/p521sig.der (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/secp256keynew.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/secp256keypubnew.pem (100%) rename {keyvault/data-plane/azure-keyvault-cryptography => sdk/keyvault/microsoft-azure-keyvault-cryptography}/src/test/resources/secp256sig.der (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/pom.xml (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/main/java/com/microsoft/azure/keyvault/extensions/AggregateKeyResolver.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/main/java/com/microsoft/azure/keyvault/extensions/CachingKeyResolver.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/main/java/com/microsoft/azure/keyvault/extensions/package.html (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/java/com/microsoft/azure/keyvault/extensions/test/CachingKeyResolverTest.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultClientIntegrationTestBase.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/resources/session-records/keyKeyVaultKeyResolverBCProviderTest.json (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/resources/session-records/keyKeyVaultKeyResolverDefaultProviderTest.json (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverBCProviderTest.json (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverDefaultProviderTest.json (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverBCProviderTest.json (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverDefaultProviderTest.json (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverBCProviderTest.json (100%) rename {keyvault/data-plane/azure-keyvault-extensions => sdk/keyvault/microsoft-azure-keyvault-extensions}/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverDefaultProviderTest.json (100%) rename {keyvault/data-plane/azure-keyvault-test => sdk/keyvault/microsoft-azure-keyvault-test}/pom.xml (100%) rename {keyvault/data-plane/azure-keyvault-test => sdk/keyvault/microsoft-azure-keyvault-test}/src/test/java/com/microsoft/azure/keyvault/test/EcKeyIntegrationTests.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/pom.xml (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/ByteExtensions.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyCurveName.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/test/java/com/microsoft/azure/keyvault/webkey/test/AesValidationTests.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/test/java/com/microsoft/azure/keyvault/webkey/test/ClearMemoryTests.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcHsmValidationTests.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcValidationTests.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaHsmValidationTests.java (100%) rename {keyvault/data-plane/azure-keyvault-webkey => sdk/keyvault/microsoft-azure-keyvault-webkey}/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaValidationTests.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/pom.xml (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientBase.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientCustom.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/authentication/AuthenticationResult.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/authentication/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/implementation/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEHeader.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEObject.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSHeader.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSObject.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/messagesecurity/MessageSecurityHelper.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/messagesecurity/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/Action.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/ActionType.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/AdministratorDetails.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/Attributes.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/BackupCertificateResult.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/BackupKeyResult.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/BackupSecretResult.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/BackupStorageResult.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateAttributes.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateCreateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateImportParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateMergeParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificatePolicy.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateRestoreParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/Contact.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/Contacts.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageAccountItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/DeletionRecoveryLevel.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/Error.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/IssuerAttributes.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/IssuerCredentials.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/IssuerParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKeyCurveName.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyAttributes.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationResult.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyRestoreParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyUsageType.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultError.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyResult.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/LifetimeAction.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/OrganizationDetails.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/PageImpl.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/PendingCertificateSigningRequestResult.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionAttributes.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionCreateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionUpdateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SasTokenType.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SecretAttributes.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SecretProperties.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SecretRestoreParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SecretSetParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SecretUpdateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountAttributes.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountCreateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountItem.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountRegenerteKeyParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountUpdateParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/StorageBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/StorageRestoreParameters.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/SubjectAlternativeNames.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/Trigger.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateOperation.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/custom/IssuerBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/custom/KeyBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/custom/SecretBundle.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/custom/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/models/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/main/java/com/microsoft/azure/keyvault/requests/package-info.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/EnhancedKeyVaultTest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/ITManagedStorageAccountKey.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/crudNames.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/resources/MockUserTokenCredentials.java (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/java/com/microsoft/azure/keyvault/test/sasNames.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/backupRestoreForKeyOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/certificateAsyncForAsyncOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/certificateAsyncRequestCancellationForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/certificateContactsAsyncForAsyncOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/certificateUpdateForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/contactsCrudOperationsForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/createCertificatePemForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/createCertificatePkcs12ForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/createCsrForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/createSelfSignedCertificatePemForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/createSelfSignedCertificatePkcs12ForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/crudOperationsForKeyOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/crudOperationsForSecretOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/deserializeWithExtraFieldTestForSecretOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/disabledSecretGetForSecretOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/encryptDecryptOperationsForKeyOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/importCertificatePkcs12ForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/importKeyOperationForKeyOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/issuerAsyncForAsyncOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/issuerCrudOperationsForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/keyAsyncForAsyncOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/listCertificateVersionsForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/listCertificatesForCertificateOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/listKeyVersionsForKeyOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/listKeysForKeyOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/listSecretVersionsForSecretOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/listSecretsForSecretOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/secretAsyncForAsyncOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/signVerifyOperationsForKeyOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/testCrudOperationsForManagedStorageAccountKey.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/testSetAndGetSasDefinitionForManagedStorageAccountKey.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/transparentAuthenticationForKeyOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/transparentAuthenticationForSecretOperationsTest.json (100%) rename {keyvault/data-plane/azure-keyvault => sdk/keyvault/microsoft-azure-keyvault}/src/test/resources/session-records/wrapUnwrapOperationsForKeyOperationsTest.json (100%) rename {keyvault/data-plane => sdk/keyvault}/pom.xml (91%) rename {keyvault/data-plane => sdk/keyvault}/regenerate_and_fix_sdk.py (100%) rename {keyvault/data-plane => sdk/keyvault}/tests.yml (100%) diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index ba75290e7d9fb..9db99b9768a6a 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -34,11 +34,11 @@ known_presence_issues: - ['cognitiveservices/data-plane/vision/customvision/prediction', '#2847'] - ['cognitiveservices/data-plane/vision/customvision/training', '#2847'] - ['cognitiveservices/data-plane/vision/faceapi', '#2847'] - - ['keyvault/data-plane/azure-keyvault', '#2847'] - - ['keyvault/data-plane/azure-keyvault-core', '#2847'] - - ['keyvault/data-plane/azure-keyvault-cryptography', '#2847'] - - ['keyvault/data-plane/azure-keyvault-extensions', '#2847'] - - ['keyvault/data-plane/azure-keyvault-webkey', '#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'] - ['mediaservices/data-plane', '#2847'] - ['core/build-tools', '#2847'] - ['core/azure-core', '#2847'] @@ -58,7 +58,7 @@ known_content_issues: - ['eventgrid/data-plane/README.md', '#3113'] - ['eventhubs/data-plane/readme.md', '#3113'] - ['eventhubs/data-plane/azure-eventhubs-eph/Readme.md', '#3113'] - - ['keyvault/data-plane/README.md', '#3113'] + - ['sdk/keyvault/README.md', '#3113'] - ['loganalytics/data-plane/README.md', '#3113'] - ['sdk/servicebus/README.md', '#3113'] - ['storage/data-plane/README.md', '#3113'] diff --git a/pom.data.xml b/pom.data.xml index 754a9e3286be0..f31baec098074 100644 --- a/pom.data.xml +++ b/pom.data.xml @@ -543,7 +543,7 @@ ./sdk/batch/microsoft-azure-batch ./eventhubs/data-plane - ./keyvault/data-plane + ./sdk/keyvault ./sdk/servicebus ./storage/data-plane diff --git a/keyvault/data-plane/.gitignore b/sdk/keyvault/.gitignore similarity index 100% rename from keyvault/data-plane/.gitignore rename to sdk/keyvault/.gitignore diff --git a/keyvault/data-plane/LICENSE b/sdk/keyvault/LICENSE similarity index 100% rename from keyvault/data-plane/LICENSE rename to sdk/keyvault/LICENSE diff --git a/keyvault/data-plane/README.md b/sdk/keyvault/README.md similarity index 100% rename from keyvault/data-plane/README.md rename to sdk/keyvault/README.md diff --git a/keyvault/data-plane/REGENERATING.md b/sdk/keyvault/REGENERATING.md similarity index 100% rename from keyvault/data-plane/REGENERATING.md rename to sdk/keyvault/REGENERATING.md diff --git a/keyvault/data-plane/history.md b/sdk/keyvault/history.md similarity index 100% rename from keyvault/data-plane/history.md rename to sdk/keyvault/history.md diff --git a/keyvault/data-plane/azure-keyvault-complete/pom.xml b/sdk/keyvault/microsoft-azure-keyvault-complete/pom.xml similarity index 100% rename from keyvault/data-plane/azure-keyvault-complete/pom.xml rename to sdk/keyvault/microsoft-azure-keyvault-complete/pom.xml diff --git a/keyvault/data-plane/azure-keyvault-core/pom.xml b/sdk/keyvault/microsoft-azure-keyvault-core/pom.xml similarity index 100% rename from keyvault/data-plane/azure-keyvault-core/pom.xml rename to sdk/keyvault/microsoft-azure-keyvault-core/pom.xml diff --git a/keyvault/data-plane/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java b/sdk/keyvault/microsoft-azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java rename to sdk/keyvault/microsoft-azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKey.java diff --git a/keyvault/data-plane/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKeyResolver.java b/sdk/keyvault/microsoft-azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKeyResolver.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKeyResolver.java rename to sdk/keyvault/microsoft-azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/IKeyResolver.java diff --git a/keyvault/data-plane/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/package-info.java b/sdk/keyvault/microsoft-azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault-core/src/main/java/com/microsoft/azure/keyvault/core/package-info.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/pom.xml b/sdk/keyvault/microsoft-azure-keyvault-cryptography/pom.xml similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/pom.xml rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/pom.xml diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Algorithm.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AlgorithmResolver.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricEncryptionAlgorithm.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/AsymmetricSignatureAlgorithm.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ByteExtensions.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EcKey.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EcKey.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EcKey.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EcKey.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/EncryptionAlgorithm.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/IAuthenticatedCryptoTransform.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ICryptoTransform.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/ISignatureTransform.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/KeyWrapAlgorithm.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/RsaKey.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureAlgorithm.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureEncoding.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureEncoding.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureEncoding.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SignatureEncoding.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/Strings.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricEncryptionAlgorithm.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/SymmetricKey.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128Cbc.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes128CbcHmacSha256.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192Cbc.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes192CbcHmacSha384.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256Cbc.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Aes256CbcHmacSha512.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbc.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesCbcHmacSha2.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw128.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw192.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/AesKw256.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Ecdsa.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Ecdsa.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Ecdsa.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Ecdsa.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256k.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256k.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256k.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es256k.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es384.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es384.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es384.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es384.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es512.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es512.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es512.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Es512.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rs256.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/Rsa15.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaEncryption.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaOaep.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/RsaSignature.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/algorithms/package-info.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/main/java/com/microsoft/azure/keyvault/cryptography/package-info.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcBCProviderTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaBCProviderTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcHmacShaTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesCbcTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwBCProviderTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/AesKwTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyBCProviderTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyBCProviderTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyBCProviderTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyBCProviderTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/ECKeyTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/PemFile.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/PemFile.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/PemFile.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/PemFile.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyBCProviderTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/RsaKeyTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyBCProviderTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/java/com/microsoft/azure/keyvault/cryptography/test/SymmetricKeyTest.java diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/SECP256key.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/SECP256key.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/SECP256key.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/SECP256key.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/byte_array.bin b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/byte_array.bin similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/byte_array.bin rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/byte_array.bin diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p256key.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p256key.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p256key.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p256key.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p256keynew.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p256keynew.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p256keynew.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p256keynew.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p256keypubnew.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p256keypubnew.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p256keypubnew.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p256keypubnew.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p256sig.der b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p256sig.der similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p256sig.der rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p256sig.der diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p384keynew.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p384keynew.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p384keynew.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p384keynew.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p384keypubnew.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p384keypubnew.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p384keypubnew.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p384keypubnew.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p384sig.der b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p384sig.der similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p384sig.der rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p384sig.der diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p521keynew.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p521keynew.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p521keynew.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p521keynew.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p521keypubnew.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p521keypubnew.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p521keypubnew.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p521keypubnew.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p521sig.der b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p521sig.der similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/p521sig.der rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/p521sig.der diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/secp256keynew.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/secp256keynew.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/secp256keynew.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/secp256keynew.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/secp256keypubnew.pem b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/secp256keypubnew.pem similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/secp256keypubnew.pem rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/secp256keypubnew.pem diff --git a/keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/secp256sig.der b/sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/secp256sig.der similarity index 100% rename from keyvault/data-plane/azure-keyvault-cryptography/src/test/resources/secp256sig.der rename to sdk/keyvault/microsoft-azure-keyvault-cryptography/src/test/resources/secp256sig.der diff --git a/keyvault/data-plane/azure-keyvault-extensions/pom.xml b/sdk/keyvault/microsoft-azure-keyvault-extensions/pom.xml similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/pom.xml rename to sdk/keyvault/microsoft-azure-keyvault-extensions/pom.xml diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/AggregateKeyResolver.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/AggregateKeyResolver.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/AggregateKeyResolver.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/AggregateKeyResolver.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/CachingKeyResolver.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/CachingKeyResolver.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/CachingKeyResolver.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/CachingKeyResolver.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKey.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/KeyVaultKeyResolver.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/Strings.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/package.html b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/package.html similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/package.html rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/main/java/com/microsoft/azure/keyvault/extensions/package.html diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/CachingKeyResolverTest.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/CachingKeyResolverTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/CachingKeyResolverTest.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/CachingKeyResolverTest.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultClientIntegrationTestBase.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultClientIntegrationTestBase.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultClientIntegrationTestBase.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultClientIntegrationTestBase.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverBCProviderTest.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/java/com/microsoft/azure/keyvault/extensions/test/KeyVaultKeyResolverDefaultProviderTest.java diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/keyKeyVaultKeyResolverBCProviderTest.json b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/keyKeyVaultKeyResolverBCProviderTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/keyKeyVaultKeyResolverBCProviderTest.json rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/keyKeyVaultKeyResolverBCProviderTest.json diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/keyKeyVaultKeyResolverDefaultProviderTest.json b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/keyKeyVaultKeyResolverDefaultProviderTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/keyKeyVaultKeyResolverDefaultProviderTest.json rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/keyKeyVaultKeyResolverDefaultProviderTest.json diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverBCProviderTest.json b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverBCProviderTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverBCProviderTest.json rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverBCProviderTest.json diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverDefaultProviderTest.json b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverDefaultProviderTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverDefaultProviderTest.json rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret128Base64KeyVaultKeyResolverDefaultProviderTest.json diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverBCProviderTest.json b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverBCProviderTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverBCProviderTest.json rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverBCProviderTest.json diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverDefaultProviderTest.json b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverDefaultProviderTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverDefaultProviderTest.json rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret192Base64KeyVaultKeyResolverDefaultProviderTest.json diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverBCProviderTest.json b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverBCProviderTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverBCProviderTest.json rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverBCProviderTest.json diff --git a/keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverDefaultProviderTest.json b/sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverDefaultProviderTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault-extensions/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverDefaultProviderTest.json rename to sdk/keyvault/microsoft-azure-keyvault-extensions/src/test/resources/session-records/secret256Base64KeyVaultKeyResolverDefaultProviderTest.json diff --git a/keyvault/data-plane/azure-keyvault-test/pom.xml b/sdk/keyvault/microsoft-azure-keyvault-test/pom.xml similarity index 100% rename from keyvault/data-plane/azure-keyvault-test/pom.xml rename to sdk/keyvault/microsoft-azure-keyvault-test/pom.xml diff --git a/keyvault/data-plane/azure-keyvault-test/src/test/java/com/microsoft/azure/keyvault/test/EcKeyIntegrationTests.java b/sdk/keyvault/microsoft-azure-keyvault-test/src/test/java/com/microsoft/azure/keyvault/test/EcKeyIntegrationTests.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-test/src/test/java/com/microsoft/azure/keyvault/test/EcKeyIntegrationTests.java rename to sdk/keyvault/microsoft-azure-keyvault-test/src/test/java/com/microsoft/azure/keyvault/test/EcKeyIntegrationTests.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/pom.xml b/sdk/keyvault/microsoft-azure-keyvault-webkey/pom.xml similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/pom.xml rename to sdk/keyvault/microsoft-azure-keyvault-webkey/pom.xml diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonDeserializer.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/Base64UrlJsonSerializer.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/ByteExtensions.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/ByteExtensions.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/ByteExtensions.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/ByteExtensions.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyCurveName.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyCurveName.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyCurveName.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyCurveName.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyEncryptionAlgorithm.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyOperation.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeySignatureAlgorithm.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKeyType.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/package-info.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/AesValidationTests.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/AesValidationTests.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/AesValidationTests.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/AesValidationTests.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/ClearMemoryTests.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/ClearMemoryTests.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/ClearMemoryTests.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/ClearMemoryTests.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcHsmValidationTests.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcHsmValidationTests.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcHsmValidationTests.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcHsmValidationTests.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcValidationTests.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcValidationTests.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcValidationTests.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/EcValidationTests.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaHsmValidationTests.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaHsmValidationTests.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaHsmValidationTests.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaHsmValidationTests.java diff --git a/keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaValidationTests.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaValidationTests.java similarity index 100% rename from keyvault/data-plane/azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaValidationTests.java rename to sdk/keyvault/microsoft-azure-keyvault-webkey/src/test/java/com/microsoft/azure/keyvault/webkey/test/RsaValidationTests.java diff --git a/keyvault/data-plane/azure-keyvault/pom.xml b/sdk/keyvault/microsoft-azure-keyvault/pom.xml similarity index 100% rename from keyvault/data-plane/azure-keyvault/pom.xml rename to sdk/keyvault/microsoft-azure-keyvault/pom.xml diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateIdentifier.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/CertificateOperationIdentifier.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/IssuerIdentifier.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyIdentifier.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClient.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientBase.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientBase.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientBase.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientBase.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientCustom.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientCustom.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientCustom.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientCustom.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/KeyVaultClientImpl.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/ObjectIdentifier.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/SecretIdentifier.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/AuthenticationResult.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/AuthenticationResult.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/AuthenticationResult.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/AuthenticationResult.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/ChallengeCache.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/KeyVaultCredentials.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/package-info.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/authentication/package-info.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientCustomImpl.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/package-info.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/package-info.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/HttpMessageSecurity.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEHeader.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEHeader.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEHeader.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEHeader.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEObject.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEObject.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEObject.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWEObject.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSHeader.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSHeader.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSHeader.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSHeader.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSObject.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSObject.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSObject.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/JWSObject.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/MessageSecurityHelper.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/MessageSecurityHelper.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/MessageSecurityHelper.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/MessageSecurityHelper.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/package-info.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/messagesecurity/package-info.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Action.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Action.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Action.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Action.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/ActionType.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/ActionType.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/ActionType.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/ActionType.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/AdministratorDetails.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/AdministratorDetails.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/AdministratorDetails.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/AdministratorDetails.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Attributes.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Attributes.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Attributes.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Attributes.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupCertificateResult.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupCertificateResult.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupCertificateResult.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupCertificateResult.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupKeyResult.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupKeyResult.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupKeyResult.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupKeyResult.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupSecretResult.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupSecretResult.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupSecretResult.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupSecretResult.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupStorageResult.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupStorageResult.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupStorageResult.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/BackupStorageResult.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateAttributes.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateAttributes.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateAttributes.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateAttributes.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateCreateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateCreateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateCreateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateCreateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateImportParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateImportParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateImportParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateImportParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerSetParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateIssuerUpdateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateMergeParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateMergeParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateMergeParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateMergeParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperation.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateOperationUpdateParameter.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificatePolicy.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificatePolicy.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificatePolicy.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificatePolicy.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateRestoreParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateRestoreParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateRestoreParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateRestoreParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/CertificateUpdateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contact.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contact.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contact.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contact.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contacts.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contacts.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contacts.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Contacts.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedCertificateItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedKeyItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSasDefinitionItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedSecretItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageAccountItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageAccountItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageAccountItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageAccountItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletedStorageBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletionRecoveryLevel.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletionRecoveryLevel.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletionRecoveryLevel.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/DeletionRecoveryLevel.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Error.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Error.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Error.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Error.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerAttributes.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerAttributes.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerAttributes.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerAttributes.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerCredentials.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerCredentials.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerCredentials.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerCredentials.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/IssuerParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKeyCurveName.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKeyCurveName.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKeyCurveName.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/JsonWebKeyCurveName.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyAttributes.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyAttributes.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyAttributes.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyAttributes.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyCreateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyImportParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationResult.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationResult.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationResult.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationResult.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyOperationsParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyProperties.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyRestoreParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyRestoreParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyRestoreParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyRestoreParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeySignParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUpdateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUsageType.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUsageType.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUsageType.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyUsageType.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultError.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultError.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultError.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultError.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVaultErrorException.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyResult.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyResult.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyResult.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/KeyVerifyResult.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/LifetimeAction.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/LifetimeAction.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/LifetimeAction.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/LifetimeAction.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/OrganizationDetails.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/OrganizationDetails.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/OrganizationDetails.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/OrganizationDetails.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PageImpl.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PageImpl.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PageImpl.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PageImpl.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PendingCertificateSigningRequestResult.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PendingCertificateSigningRequestResult.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PendingCertificateSigningRequestResult.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/PendingCertificateSigningRequestResult.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionAttributes.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionAttributes.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionAttributes.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionAttributes.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionCreateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionCreateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionCreateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionCreateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionUpdateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionUpdateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionUpdateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasDefinitionUpdateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasTokenType.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasTokenType.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasTokenType.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SasTokenType.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretAttributes.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretAttributes.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretAttributes.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretAttributes.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretProperties.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretProperties.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretProperties.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretProperties.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretRestoreParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretRestoreParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretRestoreParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretRestoreParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretSetParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretSetParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretSetParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretSetParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretUpdateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretUpdateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretUpdateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SecretUpdateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountAttributes.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountAttributes.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountAttributes.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountAttributes.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountCreateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountCreateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountCreateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountCreateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountItem.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountItem.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountItem.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountItem.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountRegenerteKeyParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountRegenerteKeyParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountRegenerteKeyParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountRegenerteKeyParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountUpdateParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountUpdateParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountUpdateParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageAccountUpdateParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageRestoreParameters.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageRestoreParameters.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageRestoreParameters.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/StorageRestoreParameters.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SubjectAlternativeNames.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SubjectAlternativeNames.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SubjectAlternativeNames.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/SubjectAlternativeNames.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Trigger.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Trigger.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Trigger.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/Trigger.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/X509CertificateProperties.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateOperation.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateOperation.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateOperation.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/CertificateOperation.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/IssuerBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/IssuerBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/IssuerBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/IssuerBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/KeyBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/KeyBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/KeyBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/KeyBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/SecretBundle.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/SecretBundle.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/SecretBundle.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/SecretBundle.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/package-info.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/custom/package-info.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/package-info.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/models/package-info.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/package-info.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/package-info.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateCertificateRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/CreateKeyRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportCertificateRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/ImportKeyRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/MergeCertificateRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetCertificateIssuerRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/SetSecretRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateIssuerRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateOperationRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificatePolicyRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateCertificateRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateKeyRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/UpdateSecretRequest.java diff --git a/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/package-info.java b/sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/package-info.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/package-info.java rename to sdk/keyvault/microsoft-azure-keyvault/src/main/java/com/microsoft/azure/keyvault/requests/package-info.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/AsyncOperationsTest.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/CertificateOperationsTest.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/EnhancedKeyVaultTest.java b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/EnhancedKeyVaultTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/EnhancedKeyVaultTest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/EnhancedKeyVaultTest.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/ITManagedStorageAccountKey.java b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/ITManagedStorageAccountKey.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/ITManagedStorageAccountKey.java rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/ITManagedStorageAccountKey.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyOperationsTest.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/KeyVaultClientIntegrationTestBase.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/SecretOperationsTest.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/crudNames.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/crudNames.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/crudNames.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/crudNames.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/resources/MockUserTokenCredentials.java b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/resources/MockUserTokenCredentials.java similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/resources/MockUserTokenCredentials.java rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/resources/MockUserTokenCredentials.java diff --git a/keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/sasNames.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/sasNames.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/sasNames.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/java/com/microsoft/azure/keyvault/test/sasNames.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/backupRestoreForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/backupRestoreForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/backupRestoreForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/backupRestoreForKeyOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/certificateAsyncForAsyncOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/certificateAsyncForAsyncOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/certificateAsyncForAsyncOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/certificateAsyncForAsyncOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/certificateAsyncRequestCancellationForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/certificateAsyncRequestCancellationForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/certificateAsyncRequestCancellationForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/certificateAsyncRequestCancellationForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/certificateContactsAsyncForAsyncOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/certificateContactsAsyncForAsyncOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/certificateContactsAsyncForAsyncOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/certificateContactsAsyncForAsyncOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/certificateUpdateForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/certificateUpdateForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/certificateUpdateForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/certificateUpdateForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/contactsCrudOperationsForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/contactsCrudOperationsForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/contactsCrudOperationsForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/contactsCrudOperationsForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createCertificatePemForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createCertificatePemForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createCertificatePemForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createCertificatePemForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createCertificatePkcs12ForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createCertificatePkcs12ForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createCertificatePkcs12ForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createCertificatePkcs12ForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createCsrForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createCsrForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createCsrForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createCsrForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createSelfSignedCertificatePemForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createSelfSignedCertificatePemForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createSelfSignedCertificatePemForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createSelfSignedCertificatePemForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createSelfSignedCertificatePkcs12ForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createSelfSignedCertificatePkcs12ForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/createSelfSignedCertificatePkcs12ForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/createSelfSignedCertificatePkcs12ForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/crudOperationsForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/crudOperationsForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/crudOperationsForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/crudOperationsForKeyOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/crudOperationsForSecretOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/crudOperationsForSecretOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/crudOperationsForSecretOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/crudOperationsForSecretOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/deserializeWithExtraFieldTestForSecretOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/deserializeWithExtraFieldTestForSecretOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/deserializeWithExtraFieldTestForSecretOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/deserializeWithExtraFieldTestForSecretOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/disabledSecretGetForSecretOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/disabledSecretGetForSecretOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/disabledSecretGetForSecretOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/disabledSecretGetForSecretOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/encryptDecryptOperationsForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/encryptDecryptOperationsForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/encryptDecryptOperationsForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/encryptDecryptOperationsForKeyOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/importCertificatePkcs12ForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/importCertificatePkcs12ForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/importCertificatePkcs12ForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/importCertificatePkcs12ForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/importKeyOperationForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/importKeyOperationForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/importKeyOperationForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/importKeyOperationForKeyOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/issuerAsyncForAsyncOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/issuerAsyncForAsyncOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/issuerAsyncForAsyncOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/issuerAsyncForAsyncOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/issuerCrudOperationsForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/issuerCrudOperationsForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/issuerCrudOperationsForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/issuerCrudOperationsForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/keyAsyncForAsyncOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/keyAsyncForAsyncOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/keyAsyncForAsyncOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/keyAsyncForAsyncOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listCertificateVersionsForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listCertificateVersionsForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listCertificateVersionsForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listCertificateVersionsForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listCertificatesForCertificateOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listCertificatesForCertificateOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listCertificatesForCertificateOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listCertificatesForCertificateOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listKeyVersionsForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listKeyVersionsForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listKeyVersionsForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listKeyVersionsForKeyOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listKeysForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listKeysForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listKeysForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listKeysForKeyOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listSecretVersionsForSecretOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listSecretVersionsForSecretOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listSecretVersionsForSecretOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listSecretVersionsForSecretOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listSecretsForSecretOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listSecretsForSecretOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/listSecretsForSecretOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/listSecretsForSecretOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/secretAsyncForAsyncOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/secretAsyncForAsyncOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/secretAsyncForAsyncOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/secretAsyncForAsyncOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/signVerifyOperationsForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/signVerifyOperationsForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/signVerifyOperationsForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/signVerifyOperationsForKeyOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/testCrudOperationsForManagedStorageAccountKey.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/testCrudOperationsForManagedStorageAccountKey.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/testCrudOperationsForManagedStorageAccountKey.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/testCrudOperationsForManagedStorageAccountKey.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/testSetAndGetSasDefinitionForManagedStorageAccountKey.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/testSetAndGetSasDefinitionForManagedStorageAccountKey.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/testSetAndGetSasDefinitionForManagedStorageAccountKey.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/testSetAndGetSasDefinitionForManagedStorageAccountKey.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/transparentAuthenticationForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/transparentAuthenticationForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/transparentAuthenticationForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/transparentAuthenticationForKeyOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/transparentAuthenticationForSecretOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/transparentAuthenticationForSecretOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/transparentAuthenticationForSecretOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/transparentAuthenticationForSecretOperationsTest.json diff --git a/keyvault/data-plane/azure-keyvault/src/test/resources/session-records/wrapUnwrapOperationsForKeyOperationsTest.json b/sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/wrapUnwrapOperationsForKeyOperationsTest.json similarity index 100% rename from keyvault/data-plane/azure-keyvault/src/test/resources/session-records/wrapUnwrapOperationsForKeyOperationsTest.json rename to sdk/keyvault/microsoft-azure-keyvault/src/test/resources/session-records/wrapUnwrapOperationsForKeyOperationsTest.json diff --git a/sdk/keyvault/pom.service.xml b/sdk/keyvault/pom.service.xml index ffc5061e45ff4..56f12fc9d934b 100644 --- a/sdk/keyvault/pom.service.xml +++ b/sdk/keyvault/pom.service.xml @@ -10,5 +10,10 @@ 1.0.0 microsoft-azure-keyvault + microsoft-azure-keyvault-core + microsoft-azure-keyvault-webkey + microsoft-azure-keyvault-cryptography + microsoft-azure-keyvault-extensions + microsoft-azure-keyvault-complete diff --git a/keyvault/data-plane/pom.xml b/sdk/keyvault/pom.xml similarity index 91% rename from keyvault/data-plane/pom.xml rename to sdk/keyvault/pom.xml index c3bac6c2f660a..4b08446c9a71d 100644 --- a/keyvault/data-plane/pom.xml +++ b/sdk/keyvault/pom.xml @@ -110,11 +110,11 @@ - ./azure-keyvault - ./azure-keyvault-core - ./azure-keyvault-webkey - ./azure-keyvault-cryptography - ./azure-keyvault-extensions - ./azure-keyvault-complete + microsoft-azure-keyvault + microsoft-azure-keyvault-core + microsoft-azure-keyvault-webkey + microsoft-azure-keyvault-cryptography + microsoft-azure-keyvault-extensions + microsoft-azure-keyvault-complete diff --git a/keyvault/data-plane/regenerate_and_fix_sdk.py b/sdk/keyvault/regenerate_and_fix_sdk.py similarity index 100% rename from keyvault/data-plane/regenerate_and_fix_sdk.py rename to sdk/keyvault/regenerate_and_fix_sdk.py diff --git a/keyvault/data-plane/tests.yml b/sdk/keyvault/tests.yml similarity index 100% rename from keyvault/data-plane/tests.yml rename to sdk/keyvault/tests.yml From bda5512f9e9c6dbac039078763fac0ea724b5103 Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Tue, 2 Jul 2019 10:16:43 -0700 Subject: [PATCH 062/147] Update preview version (#4209) * Update preview version for core and bump parent version * Update parent pom version * Update parent version for sdk template * Use plugin to update version * Add version to azure-core --- appconfiguration/client/pom.xml | 2 +- core/azure-core-amqp/pom.xml | 7 +++---- core/azure-core-management/pom.xml | 9 ++++----- core/azure-core-test/pom.xml | 7 +++---- core/azure-core/pom.xml | 4 ++-- core/pom.xml | 5 ++--- eng/jacoco-test-coverage/pom.xml | 2 +- eng/spotbugs-aggregate-report/pom.xml | 2 +- eventhubs/client/pom.xml | 2 +- eventhubs/data-plane/pom.xml | 2 +- identity/client/pom.xml | 2 +- keyvault/client/pom.xml | 2 +- keyvault/data-plane/pom.xml | 2 +- parent/pom.xml | 2 +- pom.client.xml | 4 ++-- pom.data.xml | 4 ++-- pom.management.xml | 2 +- pom.xml | 2 +- sdk/batch/microsoft-azure-batch/pom.xml | 2 +- sdk/servicebus/pom.xml | 2 +- sdk/template/azure-sdk-template/pom.xml | 2 +- storage/data-plane/pom.xml | 2 +- tracing/pom.xml | 2 +- 23 files changed, 34 insertions(+), 38 deletions(-) diff --git a/appconfiguration/client/pom.xml b/appconfiguration/client/pom.xml index 457fed3587a86..3b3ca521e268a 100644 --- a/appconfiguration/client/pom.xml +++ b/appconfiguration/client/pom.xml @@ -7,7 +7,7 @@ com.azure azure-client-sdk-parent - 1.0.0 + 1.1.0 ../../pom.client.xml diff --git a/core/azure-core-amqp/pom.xml b/core/azure-core-amqp/pom.xml index acfe076ba804c..d7a6f7eb95745 100644 --- a/core/azure-core-amqp/pom.xml +++ b/core/azure-core-amqp/pom.xml @@ -7,13 +7,13 @@ com.azure azure-core-parent - 1.0.0-preview.1 + 1.0.0-preview.2 ../pom.xml com.azure azure-core-amqp - 1.0.0-preview.1 + 1.0.0-preview.2 jar Microsoft Azure Java Core AMQP Library @@ -39,7 +39,6 @@ https://github.com/Azure/azure-sdk-for-java scm:git:https://github.com/Azure/azure-sdk-for-java.git scm:git:https://github.com/Azure/azure-sdk-for-java.git - v1.0.0-preview.1 @@ -58,7 +57,7 @@ com.azure azure-core - 1.0.0-preview.1 + 1.0.0-preview.2 diff --git a/core/azure-core-management/pom.xml b/core/azure-core-management/pom.xml index 6a08d646434e5..f811612fe7d06 100644 --- a/core/azure-core-management/pom.xml +++ b/core/azure-core-management/pom.xml @@ -7,13 +7,13 @@ com.azure azure-core-parent - 1.0.0-preview.1 + 1.0.0-preview.2 ../pom.xml com.azure azure-core-management - 1.0.0-preview.1 + 1.0.0-preview.2 jar Microsoft Azure Management Java Core Library @@ -39,7 +39,6 @@ https://github.com/Azure/azure-sdk-for-java scm:git:https://github.com/Azure/azure-sdk-for-java.git scm:git:https://github.com/Azure/azure-sdk-for-java.git - v1.0.0-preview.1 @@ -58,7 +57,7 @@ com.azure azure-core - 1.0.0-preview.1 + 1.0.0-preview.2 @@ -70,7 +69,7 @@ com.azure azure-core-test - 1.0.0-preview.1 + 1.0.0-preview.2 test diff --git a/core/azure-core-test/pom.xml b/core/azure-core-test/pom.xml index d19277735ba2b..4e4491e7e3d80 100644 --- a/core/azure-core-test/pom.xml +++ b/core/azure-core-test/pom.xml @@ -5,14 +5,14 @@ com.azure azure-core-parent - 1.0.0-preview.1 + 1.0.0-preview.2 ../pom.xml com.azure azure-core-test jar - 1.0.0-preview.1 + 1.0.0-preview.2 Microsoft Azure Java Core Test Library This package contains core test types for Azure Java clients. @@ -29,14 +29,13 @@ https://github.com/Azure/azure-sdk-for-java scm:git:https://github.com/Azure/azure-sdk-for-java.git scm:git:https://github.com/Azure/azure-sdk-for-java.git - v1.0.0-preview.1 com.azure azure-core - 1.0.0-preview.1 + 1.0.0-preview.2 diff --git a/core/azure-core/pom.xml b/core/azure-core/pom.xml index 032f2e39f5dfb..c79a490efb805 100644 --- a/core/azure-core/pom.xml +++ b/core/azure-core/pom.xml @@ -7,13 +7,14 @@ com.azure azure-core-parent - 1.0.0-preview.1 + 1.0.0-preview.2 ../pom.xml com.azure azure-core jar + 1.0.0-preview.2 Microsoft Azure Java Core Library This package contains core types for Azure Java clients. @@ -38,7 +39,6 @@ https://github.com/Azure/azure-sdk-for-java scm:git:https://github.com/Azure/azure-sdk-for-java.git scm:git:https://github.com/Azure/azure-sdk-for-java.git - v1.0.0-preview.1 diff --git a/core/pom.xml b/core/pom.xml index 4f6a7ce87ce25..09d9fddefb8d5 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -8,13 +8,13 @@ com.azure azure-client-sdk-parent - 1.0.0 + 1.1.0 ../pom.client.xml com.azure azure-core-parent - 1.0.0-preview.1 + 1.0.0-preview.2 pom Microsoft Azure Core Libraries for Java @@ -33,7 +33,6 @@ scm:git:https://github.com/Azure/azure-sdk-for-java scm:git:https://github.com/Azure/azure-sdk-for-java.git scm:git:https://github.com/Azure/azure-sdk-for-java.git - v1.0.0-preview.1 diff --git a/eng/jacoco-test-coverage/pom.xml b/eng/jacoco-test-coverage/pom.xml index 82ed0618208a7..0af2cfee8b3f9 100644 --- a/eng/jacoco-test-coverage/pom.xml +++ b/eng/jacoco-test-coverage/pom.xml @@ -10,7 +10,7 @@ com.azure azure-client-sdk-parent - 1.0.0 + 1.1.0 ../../pom.client.xml diff --git a/eng/spotbugs-aggregate-report/pom.xml b/eng/spotbugs-aggregate-report/pom.xml index 0e9be8f52c13d..1b6da34c6bf24 100644 --- a/eng/spotbugs-aggregate-report/pom.xml +++ b/eng/spotbugs-aggregate-report/pom.xml @@ -6,7 +6,7 @@ azure-client-sdk-parent com.azure - 1.0.0 + 1.1.0 ../../pom.client.xml 4.0.0 diff --git a/eventhubs/client/pom.xml b/eventhubs/client/pom.xml index 349a20ea12b0e..bc86a93bfeb5e 100644 --- a/eventhubs/client/pom.xml +++ b/eventhubs/client/pom.xml @@ -8,7 +8,7 @@ com.azure azure-client-sdk-parent - 1.0.0 + 1.1.0 ../../pom.client.xml diff --git a/eventhubs/data-plane/pom.xml b/eventhubs/data-plane/pom.xml index 3c1235e0732c8..72c5ab14aa8b1 100644 --- a/eventhubs/data-plane/pom.xml +++ b/eventhubs/data-plane/pom.xml @@ -7,7 +7,7 @@ com.azure azure-data-sdk-parent - 1.0.0 + 1.1.0 ../../pom.data.xml diff --git a/identity/client/pom.xml b/identity/client/pom.xml index 64ccae2bceccc..9d1942e263114 100644 --- a/identity/client/pom.xml +++ b/identity/client/pom.xml @@ -11,7 +11,7 @@ com.azure azure-client-sdk-parent - 1.0.0 + 1.1.0 ../../pom.client.xml diff --git a/keyvault/client/pom.xml b/keyvault/client/pom.xml index 70be876c33f2d..5f0a2d8a7e05c 100644 --- a/keyvault/client/pom.xml +++ b/keyvault/client/pom.xml @@ -6,7 +6,7 @@ com.azure azure-client-sdk-parent - 1.0.0 + 1.1.0 ../../pom.client.xml diff --git a/keyvault/data-plane/pom.xml b/keyvault/data-plane/pom.xml index c3bac6c2f660a..ac01e71f00637 100644 --- a/keyvault/data-plane/pom.xml +++ b/keyvault/data-plane/pom.xml @@ -9,7 +9,7 @@ com.azure azure-data-sdk-parent - 1.0.0 + 1.1.0 ../../pom.data.xml diff --git a/parent/pom.xml b/parent/pom.xml index 6a5873e491ecf..792bd863e1d8a 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -6,7 +6,7 @@ com.azure azure-sdk-parent pom - 1.0.0 + 1.1.0 Microsoft Azure SDK for Java Parent Parent POM for Microsoft Azure SDK for Java diff --git a/pom.client.xml b/pom.client.xml index 5979de4e41b1f..dfbc315cf5a37 100644 --- a/pom.client.xml +++ b/pom.client.xml @@ -6,7 +6,7 @@ com.azure azure-client-sdk-parent pom - 1.0.0 + 1.1.0 Microsoft Azure SDK for Java - Client Libraries Parent POM for Microsoft Azure SDK for Java @@ -19,7 +19,7 @@ com.azure azure-sdk-parent - 1.0.0 + 1.1.0 ./parent/pom.xml diff --git a/pom.data.xml b/pom.data.xml index 754a9e3286be0..1a802715a3b5c 100644 --- a/pom.data.xml +++ b/pom.data.xml @@ -6,7 +6,7 @@ com.azure azure-data-sdk-parent pom - 1.0.0 + 1.1.0 Microsoft Azure SDK for Java - Data Plane Libraries Parent POM for Microsoft Azure SDK for Java @@ -19,7 +19,7 @@ com.azure azure-sdk-parent - 1.0.0 + 1.1.0 ./parent/pom.xml diff --git a/pom.management.xml b/pom.management.xml index b3e54a8c50355..42f888594ed23 100644 --- a/pom.management.xml +++ b/pom.management.xml @@ -21,7 +21,7 @@ com.azure azure-sdk-parent - 1.0.0 + 1.1.0 ./parent/pom.xml diff --git a/pom.xml b/pom.xml index 04446fa2474fa..125c326f84890 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ com.azure azure-sdk-parent - 1.0.0 + 1.1.0 ./parent/pom.xml diff --git a/sdk/batch/microsoft-azure-batch/pom.xml b/sdk/batch/microsoft-azure-batch/pom.xml index 3bf92495e4fdc..43795fd55d08d 100644 --- a/sdk/batch/microsoft-azure-batch/pom.xml +++ b/sdk/batch/microsoft-azure-batch/pom.xml @@ -9,7 +9,7 @@ com.azure azure-data-sdk-parent - 1.0.0 + 1.1.0 ../../../pom.data.xml diff --git a/sdk/servicebus/pom.xml b/sdk/servicebus/pom.xml index a67dbb9efd79d..bfc3a7f2daed1 100644 --- a/sdk/servicebus/pom.xml +++ b/sdk/servicebus/pom.xml @@ -16,7 +16,7 @@ com.azure azure-data-sdk-parent - 1.0.0 + 1.1.0 ../../pom.data.xml diff --git a/sdk/template/azure-sdk-template/pom.xml b/sdk/template/azure-sdk-template/pom.xml index 576735b26541e..3c5ff41f6fc2a 100644 --- a/sdk/template/azure-sdk-template/pom.xml +++ b/sdk/template/azure-sdk-template/pom.xml @@ -5,7 +5,7 @@ com.azure azure-client-sdk-parent - 1.0.0 + 1.1.0 ../../../pom.client.xml diff --git a/storage/data-plane/pom.xml b/storage/data-plane/pom.xml index de02bb38fb1be..ef4ccc0aaa710 100644 --- a/storage/data-plane/pom.xml +++ b/storage/data-plane/pom.xml @@ -9,7 +9,7 @@ com.azure azure-data-sdk-parent - 1.0.0 + 1.1.0 ../../pom.data.xml diff --git a/tracing/pom.xml b/tracing/pom.xml index 822fab5e83b78..46a138301460c 100644 --- a/tracing/pom.xml +++ b/tracing/pom.xml @@ -8,7 +8,7 @@ com.azure azure-client-sdk-parent - 1.0.0 + 1.1.0 ../pom.client.xml From 01f35f05b16160cbc892777e84458d97a4be2873 Mon Sep 17 00:00:00 2001 From: Anu Thomas Chandy Date: Tue, 2 Jul 2019 10:22:31 -0700 Subject: [PATCH 063/147] If body is empty then return publisher emitting response instead of propagating empty publisher (#4208) --- .../main/java/com/azure/core/http/policy/HttpLoggingPolicy.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java b/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java index 9ca980855fc8d..36c29dc036f48 100644 --- a/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java +++ b/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java @@ -145,7 +145,7 @@ private Function> logResponseDelegate(final Cli logger.asInfo().log("Response body:\n{}", bodyStr); logger.asInfo().log("<-- END HTTP"); return bufferedResponse; - }); + }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.asInfo().log("(body content not logged)"); logger.asInfo().log("<-- END HTTP"); From 07e29a7fe4103d2ed8971db532e2e140d752c426 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Tue, 2 Jul 2019 11:42:48 -0700 Subject: [PATCH 064/147] Move tracing to sdk/tracing (#4147) * Base move. * Fixed up POM references. --- pom.client.xml | 2 +- {tracing => sdk/tracing}/README.md | 0 .../tracing/azure-tracing-opentelemetry}/README.md | 0 .../tracing/azure-tracing-opentelemetry}/pom.xml | 0 .../java/com/azure/tracing/opentelemetry/HttpTraceUtil.java | 0 .../azure/tracing/opentelemetry/OpenTelemetryHttpPolicy.java | 0 .../com/azure/tracing/opentelemetry/OpenTelemetryTracer.java | 0 .../java/com/azure/tracing/opentelemetry/package-info.java | 0 ...re.implementation.http.policy.spi.AfterRetryPolicyProvider | 0 .../services/com.azure.core.implementation.tracing.Tracer | 0 {tracing => sdk/tracing}/pom.xml | 4 ++-- 11 files changed, 3 insertions(+), 3 deletions(-) rename {tracing => sdk/tracing}/README.md (100%) rename {tracing/tracing-opentelemetry => sdk/tracing/azure-tracing-opentelemetry}/README.md (100%) rename {tracing/tracing-opentelemetry => sdk/tracing/azure-tracing-opentelemetry}/pom.xml (100%) rename {tracing/tracing-opentelemetry => sdk/tracing/azure-tracing-opentelemetry}/src/main/java/com/azure/tracing/opentelemetry/HttpTraceUtil.java (100%) rename {tracing/tracing-opentelemetry => sdk/tracing/azure-tracing-opentelemetry}/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryHttpPolicy.java (100%) rename {tracing/tracing-opentelemetry => sdk/tracing/azure-tracing-opentelemetry}/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryTracer.java (100%) rename {tracing/tracing-opentelemetry => sdk/tracing/azure-tracing-opentelemetry}/src/main/java/com/azure/tracing/opentelemetry/package-info.java (100%) rename {tracing/tracing-opentelemetry => sdk/tracing/azure-tracing-opentelemetry}/src/main/resources/META-INF/services/com.azure.core.implementation.http.policy.spi.AfterRetryPolicyProvider (100%) rename {tracing/tracing-opentelemetry => sdk/tracing/azure-tracing-opentelemetry}/src/main/resources/META-INF/services/com.azure.core.implementation.tracing.Tracer (100%) rename {tracing => sdk/tracing}/pom.xml (94%) diff --git a/pom.client.xml b/pom.client.xml index 5979de4e41b1f..8455e01021213 100644 --- a/pom.client.xml +++ b/pom.client.xml @@ -702,7 +702,7 @@ ./core ./eventhubs/client ./keyvault/client - ./tracing + ./sdk/tracing ./identity/client diff --git a/tracing/README.md b/sdk/tracing/README.md similarity index 100% rename from tracing/README.md rename to sdk/tracing/README.md diff --git a/tracing/tracing-opentelemetry/README.md b/sdk/tracing/azure-tracing-opentelemetry/README.md similarity index 100% rename from tracing/tracing-opentelemetry/README.md rename to sdk/tracing/azure-tracing-opentelemetry/README.md diff --git a/tracing/tracing-opentelemetry/pom.xml b/sdk/tracing/azure-tracing-opentelemetry/pom.xml similarity index 100% rename from tracing/tracing-opentelemetry/pom.xml rename to sdk/tracing/azure-tracing-opentelemetry/pom.xml diff --git a/tracing/tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/HttpTraceUtil.java b/sdk/tracing/azure-tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/HttpTraceUtil.java similarity index 100% rename from tracing/tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/HttpTraceUtil.java rename to sdk/tracing/azure-tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/HttpTraceUtil.java diff --git a/tracing/tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryHttpPolicy.java b/sdk/tracing/azure-tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryHttpPolicy.java similarity index 100% rename from tracing/tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryHttpPolicy.java rename to sdk/tracing/azure-tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryHttpPolicy.java diff --git a/tracing/tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryTracer.java b/sdk/tracing/azure-tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryTracer.java similarity index 100% rename from tracing/tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryTracer.java rename to sdk/tracing/azure-tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/OpenTelemetryTracer.java diff --git a/tracing/tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/package-info.java b/sdk/tracing/azure-tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/package-info.java similarity index 100% rename from tracing/tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/package-info.java rename to sdk/tracing/azure-tracing-opentelemetry/src/main/java/com/azure/tracing/opentelemetry/package-info.java diff --git a/tracing/tracing-opentelemetry/src/main/resources/META-INF/services/com.azure.core.implementation.http.policy.spi.AfterRetryPolicyProvider b/sdk/tracing/azure-tracing-opentelemetry/src/main/resources/META-INF/services/com.azure.core.implementation.http.policy.spi.AfterRetryPolicyProvider similarity index 100% rename from tracing/tracing-opentelemetry/src/main/resources/META-INF/services/com.azure.core.implementation.http.policy.spi.AfterRetryPolicyProvider rename to sdk/tracing/azure-tracing-opentelemetry/src/main/resources/META-INF/services/com.azure.core.implementation.http.policy.spi.AfterRetryPolicyProvider diff --git a/tracing/tracing-opentelemetry/src/main/resources/META-INF/services/com.azure.core.implementation.tracing.Tracer b/sdk/tracing/azure-tracing-opentelemetry/src/main/resources/META-INF/services/com.azure.core.implementation.tracing.Tracer similarity index 100% rename from tracing/tracing-opentelemetry/src/main/resources/META-INF/services/com.azure.core.implementation.tracing.Tracer rename to sdk/tracing/azure-tracing-opentelemetry/src/main/resources/META-INF/services/com.azure.core.implementation.tracing.Tracer diff --git a/tracing/pom.xml b/sdk/tracing/pom.xml similarity index 94% rename from tracing/pom.xml rename to sdk/tracing/pom.xml index 822fab5e83b78..c6b1bb9dde447 100644 --- a/tracing/pom.xml +++ b/sdk/tracing/pom.xml @@ -9,7 +9,7 @@ com.azure azure-client-sdk-parent 1.0.0 - ../pom.client.xml + ../../pom.client.xml com.azure @@ -53,6 +53,6 @@ - tracing-opentelemetry + azure-tracing-opentelemetry From 79c0b48351caf25d28e63756ba1bf9b657ba0560 Mon Sep 17 00:00:00 2001 From: Scott Beddall <45376673+scbedd@users.noreply.github.com> Date: Tue, 2 Jul 2019 12:17:32 -0700 Subject: [PATCH 065/147] docs.yml that outputs ref docs for java github.io (#4190) * doc yaml for generating all the api reference docs for each pomfile * index template for the repo github.io landing page --- .azure-pipelines/docs.yml | 133 ++++++++++ eng/repo-docs/index.html | 517 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 650 insertions(+) create mode 100644 .azure-pipelines/docs.yml create mode 100644 eng/repo-docs/index.html diff --git a/.azure-pipelines/docs.yml b/.azure-pipelines/docs.yml new file mode 100644 index 0000000000000..83b66b7c1c72e --- /dev/null +++ b/.azure-pipelines/docs.yml @@ -0,0 +1,133 @@ +trigger: + - master + +variables: + DefaultOptions: '--batch-mode -Dmaven.wagon.http.pool=false' + LoggingOptions: '-Dorg.slf4j.simpleLogger.defaultLogLevel=error -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn' + +jobs: + - job: 'Generate_Track_2' + variables: + skipComponentGovernanceDetection: true + timeoutInMinutes: 120 + pool: + vmImage: 'vs2017-win2016' + + steps: + - powershell: | + copy eng/repo-docs/index.html $(Build.ArtifactStagingDirectory) + displayName: 'Copy index to artifact staging' + + - task: PublishPipelineArtifact@0 + condition: succeededOrFailed() + displayName: 'Publish index artifact' + inputs: + artifactName: index + targetPath: $(Build.ArtifactStagingDirectory) + + # We `install` separately from running `site:site site:stage` so that the `install` brings in the non-shipping-modules, + # but we don't include them in the Maven site commands (so that we don't generate reports for the non-shipping modules). + - task: Maven@3 + displayName: 'Install reporting tools' + inputs: + mavenPomFile: pom.client.xml + options: '$(DefaultOptions) -Dinclude-non-shipping-modules -DskipTests -Dgpg.skip' + mavenOptions: '$(LoggingOptions)' + javaHomeOption: 'JDKVersion' + jdkVersionOption: '1.11' + jdkArchitectureOption: 'x64' + publishJUnitResults: false + goals: 'install' + + - task: Maven@3 + displayName: 'Generate Doc Site' + inputs: + mavenPomFile: pom.client.xml + options: '$(DefaultOptions) -DskipTests -Dgpg.skip' + mavenOptions: '$(LoggingOptions)' + javaHomeOption: 'JDKVersion' + jdkVersionOption: '1.11' + jdkArchitectureOption: 'x64' + publishJUnitResults: false + goals: 'site:site site:stage' + + - task: Maven@3 + displayName: 'Install azure-sdk-parent' + inputs: + mavenPomFile: parent/pom.xml + options: '$(DefaultOptions) -DskipTests -Dgpg.skip' + mavenOptions: '$(LoggingOptions)' + javaHomeOption: 'JDKVersion' + jdkVersionOption: '1.11' + jdkArchitectureOption: 'x64' + publishJUnitResults: false + goals: 'install' + + - powershell: | + copy -r target/staging/apidocs $(Build.ArtifactStagingDirectory)/client + displayName: 'Copy reports to artifact staging' + + - task: PublishPipelineArtifact@0 + condition: succeededOrFailed() + displayName: 'Publish reports artifact' + inputs: + artifactName: track2reports + targetPath: $(Build.ArtifactStagingDirectory)/client + + - job: 'Generate_Track_1' + variables: + skipComponentGovernanceDetection: true + timeoutInMinutes: 120 + pool: + vmImage: 'vs2017-win2016' + + steps: + # We `install` separately from running `site:site site:stage` so that the `install` brings in the non-shipping-modules, + # but we don't include them in the Maven site commands (so that we don't generate reports for the non-shipping modules). + - task: Maven@3 + displayName: 'Install client.xml to get spotbugs reporting' + inputs: + mavenPomFile: pom.client.xml + options: '$(DefaultOptions) -Dinclude-non-shipping-modules -Dmaven.javadoc.skip=true -DskipTests -Dgpg.skip' + mavenOptions: '$(LoggingOptions)' + javaHomeOption: 'JDKVersion' + jdkVersionOption: '1.8' + jdkArchitectureOption: 'x64' + publishJUnitResults: false + goals: 'install' + + - task: Maven@3 + displayName: 'Install Data Packages' + inputs: + mavenPomFile: pom.data.xml + options: '$(DefaultOptions) -Dinclude-non-shipping-modules -Dmaven.javadoc.skip=true -DskipTests -Dgpg.skip' + mavenOptions: '$(LoggingOptions)' + javaHomeOption: 'JDKVersion' + jdkVersionOption: '1.8' + jdkArchitectureOption: 'x64' + publishJUnitResults: false + goals: 'install' + + - task: Maven@3 + displayName: 'Generate Doc Site' + inputs: + mavenPomFile: pom.data.xml + options: '$(DefaultOptions) -DskipTests -Dgpg.skip' + mavenOptions: '$(LoggingOptions)' + javaHomeOption: 'JDKVersion' + jdkVersionOption: '1.8' + jdkArchitectureOption: 'x64' + publishJUnitResults: false + goals: 'site:site' + + - powershell: | + copy -r target/site/apidocs $(Build.ArtifactStagingDirectory)/data + displayName: 'Copy reports to artifact staging' + + - task: PublishPipelineArtifact@0 + condition: succeededOrFailed() + displayName: 'Publish reports artifact' + inputs: + artifactName: track1reports + targetPath: $(Build.ArtifactStagingDirectory)/data + diff --git a/eng/repo-docs/index.html b/eng/repo-docs/index.html new file mode 100644 index 0000000000000..3070e9acb4551 --- /dev/null +++ b/eng/repo-docs/index.html @@ -0,0 +1,517 @@ + + + + + + + + + Azure SDK For Java - Github.io Landing Page + + + + + + + + +

+
+
+ +
+

Azure Java SDK

+

Refer to the links below for reference documentation generated from the Azure SDK for Java source code.

+
+ +
+
    +
  • + Client Libraries +
  • + +
    +
  • + + JavaDocs +
  • +
    +
+
+ +
+
    +
  • + Data Libraries +
  • + +
    +
  • + + JavaDocs +
  • +
    +
+
+
+ +
+
+
+
+

Powered by Azure.

+
+
+
+
+ + + + \ No newline at end of file From 0e9a985ece3663369d88505a53b18c30e8f9f6e6 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Tue, 2 Jul 2019 14:00:08 -0700 Subject: [PATCH 066/147] updated azure-arm-client-runtime test jar dependency (#4218) --- appconfiguration/resource-manager/v2019_02_01_preview/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/appconfiguration/resource-manager/v2019_02_01_preview/pom.xml b/appconfiguration/resource-manager/v2019_02_01_preview/pom.xml index a6044c1e69bc5..b9182f0b2edb1 100644 --- a/appconfiguration/resource-manager/v2019_02_01_preview/pom.xml +++ b/appconfiguration/resource-manager/v2019_02_01_preview/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 69f562b8454b230223cfa64ccc28e33417baa768 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Tue, 2 Jul 2019 14:56:31 -0700 Subject: [PATCH 067/147] updated azure-arm-client-runtime test jar dependency (#4219) --- netapp/resource-manager/v2019_06_01/pom.xml | 2 ++ .../netapp/v2019_06_01/implementation/PoolsImpl.java | 10 +++++++--- .../v2019_06_01/implementation/SnapshotsImpl.java | 10 +++++++--- .../netapp/v2019_06_01/implementation/VolumesImpl.java | 10 +++++++--- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/netapp/resource-manager/v2019_06_01/pom.xml b/netapp/resource-manager/v2019_06_01/pom.xml index 64bb9aec1e57d..07688d78b3990 100644 --- a/netapp/resource-manager/v2019_06_01/pom.xml +++ b/netapp/resource-manager/v2019_06_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 diff --git a/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/PoolsImpl.java b/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/PoolsImpl.java index dc145cfa70b83..2243f74b09cb6 100644 --- a/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/PoolsImpl.java +++ b/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/PoolsImpl.java @@ -64,10 +64,14 @@ public CapacityPool call(CapacityPoolInner inner) { public Observable getAsync(String resourceGroupName, String accountName, String poolName) { PoolsInner client = this.inner(); return client.getAsync(resourceGroupName, accountName, poolName) - .map(new Func1() { + .flatMap(new Func1>() { @Override - public CapacityPool call(CapacityPoolInner inner) { - return wrapModel(inner); + public Observable call(CapacityPoolInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((CapacityPool)wrapModel(inner)); + } } }); } diff --git a/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/SnapshotsImpl.java b/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/SnapshotsImpl.java index 48c2a5c78ef5f..9ed6494294703 100644 --- a/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/SnapshotsImpl.java +++ b/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/SnapshotsImpl.java @@ -64,10 +64,14 @@ public Snapshot call(SnapshotInner inner) { public Observable getAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { SnapshotsInner client = this.inner(); return client.getAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName) - .map(new Func1() { + .flatMap(new Func1>() { @Override - public Snapshot call(SnapshotInner inner) { - return wrapModel(inner); + public Observable call(SnapshotInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((Snapshot)wrapModel(inner)); + } } }); } diff --git a/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/VolumesImpl.java b/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/VolumesImpl.java index 68a6022f4a777..62cd23cf29408 100644 --- a/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/VolumesImpl.java +++ b/netapp/resource-manager/v2019_06_01/src/main/java/com/microsoft/azure/management/netapp/v2019_06_01/implementation/VolumesImpl.java @@ -64,10 +64,14 @@ public Volume call(VolumeInner inner) { public Observable getAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { VolumesInner client = this.inner(); return client.getAsync(resourceGroupName, accountName, poolName, volumeName) - .map(new Func1() { + .flatMap(new Func1>() { @Override - public Volume call(VolumeInner inner) { - return wrapModel(inner); + public Observable call(VolumeInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((Volume)wrapModel(inner)); + } } }); } From c94a1756d9a65896035388180917d618e3499ddd Mon Sep 17 00:00:00 2001 From: Yaohai Zheng Date: Wed, 3 Jul 2019 07:12:58 +0800 Subject: [PATCH 068/147] Generate v2017_11_03_preview for hanaonazure (#4235) --- .../v2017_11_03_preview/pom.xml | 4 +- .../v2017_11_03_preview/HanaInstances.java | 20 + .../v2017_11_03_preview/SapMonitor.java | 247 +++++ .../v2017_11_03_preview/SapMonitors.java | 24 + .../implementation/HanaInstancesImpl.java | 12 + .../implementation/HanaInstancesInner.java | 334 +++++- .../HanaManagementClientImpl.java | 14 + .../implementation/HanaOnAzureManager.java | 12 + .../implementation/SapMonitorImpl.java | 118 +++ .../implementation/SapMonitorInner.java | 196 ++++ .../implementation/SapMonitorsImpl.java | 114 +++ .../implementation/SapMonitorsInner.java | 947 ++++++++++++++++++ 12 files changed, 2036 insertions(+), 6 deletions(-) create mode 100644 hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/SapMonitor.java create mode 100644 hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/SapMonitors.java create mode 100644 hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorImpl.java create mode 100644 hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorInner.java create mode 100644 hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorsImpl.java create mode 100644 hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorsInner.java diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/pom.xml b/hanaonazure/resource-manager/v2017_11_03_preview/pom.xml index 9d4bf5705ea10..d83c350d750c1 100644 --- a/hanaonazure/resource-manager/v2017_11_03_preview/pom.xml +++ b/hanaonazure/resource-manager/v2017_11_03_preview/pom.xml @@ -15,7 +15,7 @@ ../../../pom.management.xml azure-mgmt-hanaonazure - 1.0.0-beta-2 + 1.0.0-beta-3 jar Microsoft Azure SDK for HanaOnAzure Management This package contains Microsoft HanaOnAzure Management SDK. @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/HanaInstances.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/HanaInstances.java index f6d0fbed04ee4..dc6a6c7cd639e 100644 --- a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/HanaInstances.java +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/HanaInstances.java @@ -33,6 +33,26 @@ public interface HanaInstances extends SupportsCreating, Resource, GroupableResourceCore, HasResourceGroup, Refreshable, Updatable, HasManager { + /** + * @return the hanaDbName value. + */ + String hanaDbName(); + + /** + * @return the hanaDbPassword value. + */ + String hanaDbPassword(); + + /** + * @return the hanaDbSqlPort value. + */ + Integer hanaDbSqlPort(); + + /** + * @return the hanaDbUsername value. + */ + String hanaDbUsername(); + + /** + * @return the hanaHostname value. + */ + String hanaHostname(); + + /** + * @return the hanaSubnet value. + */ + String hanaSubnet(); + + /** + * @return the provisioningState value. + */ + HanaProvisioningStatesEnum provisioningState(); + + /** + * The entirety of the SapMonitor definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate { + } + + /** + * Grouping of SapMonitor definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a SapMonitor definition. + */ + interface Blank extends GroupableResourceCore.DefinitionWithRegion { + } + + /** + * The stage of the SapMonitor definition allowing to specify the resource group. + */ + interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup { + } + + /** + * The stage of the sapmonitor definition allowing to specify HanaDbName. + */ + interface WithHanaDbName { + /** + * Specifies hanaDbName. + * @param hanaDbName Database name of the HANA instance + * @return the next definition stage + */ + WithCreate withHanaDbName(String hanaDbName); + } + + /** + * The stage of the sapmonitor definition allowing to specify HanaDbPassword. + */ + interface WithHanaDbPassword { + /** + * Specifies hanaDbPassword. + * @param hanaDbPassword Database password of the HANA instance + * @return the next definition stage + */ + WithCreate withHanaDbPassword(String hanaDbPassword); + } + + /** + * The stage of the sapmonitor definition allowing to specify HanaDbSqlPort. + */ + interface WithHanaDbSqlPort { + /** + * Specifies hanaDbSqlPort. + * @param hanaDbSqlPort Database port of the HANA instance + * @return the next definition stage + */ + WithCreate withHanaDbSqlPort(Integer hanaDbSqlPort); + } + + /** + * The stage of the sapmonitor definition allowing to specify HanaDbUsername. + */ + interface WithHanaDbUsername { + /** + * Specifies hanaDbUsername. + * @param hanaDbUsername Database username of the HANA instance + * @return the next definition stage + */ + WithCreate withHanaDbUsername(String hanaDbUsername); + } + + /** + * The stage of the sapmonitor definition allowing to specify HanaHostname. + */ + interface WithHanaHostname { + /** + * Specifies hanaHostname. + * @param hanaHostname Hostname of the HANA instance + * @return the next definition stage + */ + WithCreate withHanaHostname(String hanaHostname); + } + + /** + * The stage of the sapmonitor definition allowing to specify HanaSubnet. + */ + interface WithHanaSubnet { + /** + * Specifies hanaSubnet. + * @param hanaSubnet Specifies the SAP monitor unique ID + * @return the next definition stage + */ + WithCreate withHanaSubnet(String hanaSubnet); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, Resource.DefinitionWithTags, DefinitionStages.WithHanaDbName, DefinitionStages.WithHanaDbPassword, DefinitionStages.WithHanaDbSqlPort, DefinitionStages.WithHanaDbUsername, DefinitionStages.WithHanaHostname, DefinitionStages.WithHanaSubnet { + } + } + /** + * The template for a SapMonitor update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithHanaDbName, UpdateStages.WithHanaDbPassword, UpdateStages.WithHanaDbSqlPort, UpdateStages.WithHanaDbUsername, UpdateStages.WithHanaHostname, UpdateStages.WithHanaSubnet { + } + + /** + * Grouping of SapMonitor update stages. + */ + interface UpdateStages { + /** + * The stage of the sapmonitor update allowing to specify HanaDbName. + */ + interface WithHanaDbName { + /** + * Specifies hanaDbName. + * @param hanaDbName Database name of the HANA instance + * @return the next update stage + */ + Update withHanaDbName(String hanaDbName); + } + + /** + * The stage of the sapmonitor update allowing to specify HanaDbPassword. + */ + interface WithHanaDbPassword { + /** + * Specifies hanaDbPassword. + * @param hanaDbPassword Database password of the HANA instance + * @return the next update stage + */ + Update withHanaDbPassword(String hanaDbPassword); + } + + /** + * The stage of the sapmonitor update allowing to specify HanaDbSqlPort. + */ + interface WithHanaDbSqlPort { + /** + * Specifies hanaDbSqlPort. + * @param hanaDbSqlPort Database port of the HANA instance + * @return the next update stage + */ + Update withHanaDbSqlPort(Integer hanaDbSqlPort); + } + + /** + * The stage of the sapmonitor update allowing to specify HanaDbUsername. + */ + interface WithHanaDbUsername { + /** + * Specifies hanaDbUsername. + * @param hanaDbUsername Database username of the HANA instance + * @return the next update stage + */ + Update withHanaDbUsername(String hanaDbUsername); + } + + /** + * The stage of the sapmonitor update allowing to specify HanaHostname. + */ + interface WithHanaHostname { + /** + * Specifies hanaHostname. + * @param hanaHostname Hostname of the HANA instance + * @return the next update stage + */ + Update withHanaHostname(String hanaHostname); + } + + /** + * The stage of the sapmonitor update allowing to specify HanaSubnet. + */ + interface WithHanaSubnet { + /** + * Specifies hanaSubnet. + * @param hanaSubnet Specifies the SAP monitor unique ID + * @return the next update stage + */ + Update withHanaSubnet(String hanaSubnet); + } + + } +} diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/SapMonitors.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/SapMonitors.java new file mode 100644 index 0000000000000..d01ca506b8992 --- /dev/null +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/SapMonitors.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.hanaonazure.v2017_11_03_preview; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import com.microsoft.azure.arm.resources.collection.SupportsDeletingByResourceGroup; +import com.microsoft.azure.arm.resources.collection.SupportsBatchDeletion; +import com.microsoft.azure.arm.resources.collection.SupportsGettingByResourceGroup; +import rx.Observable; +import com.microsoft.azure.arm.collection.SupportsListing; +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.implementation.SapMonitorsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing SapMonitors. + */ +public interface SapMonitors extends SupportsCreating, SupportsDeletingByResourceGroup, SupportsBatchDeletion, SupportsGettingByResourceGroup, SupportsListing, HasInner { +} diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaInstancesImpl.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaInstancesImpl.java index 222be84cb98fa..22f815a1c8541 100644 --- a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaInstancesImpl.java +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaInstancesImpl.java @@ -132,6 +132,18 @@ public Completable restartAsync(String resourceGroupName, String hanaInstanceNam return client.restartAsync(resourceGroupName, hanaInstanceName).toCompletable(); } + @Override + public Completable startAsync(String resourceGroupName, String hanaInstanceName) { + HanaInstancesInner client = this.inner(); + return client.startAsync(resourceGroupName, hanaInstanceName).toCompletable(); + } + + @Override + public Completable shutdownAsync(String resourceGroupName, String hanaInstanceName) { + HanaInstancesInner client = this.inner(); + return client.shutdownAsync(resourceGroupName, hanaInstanceName).toCompletable(); + } + @Override public Completable enableMonitoringAsync(String resourceGroupName, String hanaInstanceName, MonitoringDetails monitoringParameter) { HanaInstancesInner client = this.inner(); diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaInstancesInner.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaInstancesInner.java index 9d41257ad424f..f4af67cccdad0 100644 --- a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaInstancesInner.java +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaInstancesInner.java @@ -110,6 +110,22 @@ interface HanaInstancesService { @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/hanaInstances/{hanaInstanceName}/restart") Observable> beginRestart(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("hanaInstanceName") String hanaInstanceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.HanaInstances start" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/hanaInstances/{hanaInstanceName}/start") + Observable> start(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("hanaInstanceName") String hanaInstanceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.HanaInstances beginStart" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/hanaInstances/{hanaInstanceName}/start") + Observable> beginStart(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("hanaInstanceName") String hanaInstanceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.HanaInstances shutdown" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/hanaInstances/{hanaInstanceName}/shutdown") + Observable> shutdown(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("hanaInstanceName") String hanaInstanceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.HanaInstances beginShutdown" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/hanaInstances/{hanaInstanceName}/shutdown") + Observable> beginShutdown(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("hanaInstanceName") String hanaInstanceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.HanaInstances enableMonitoring" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/hanaInstances/{hanaInstanceName}/monitoring") Observable> enableMonitoring(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("hanaInstanceName") String hanaInstanceName, @Query("api-version") String apiVersion, @Body MonitoringDetails monitoringParameter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @@ -982,7 +998,7 @@ private ServiceResponse updateDelegate(Response * @param resourceGroupName Name of the resource group. * @param hanaInstanceName Name of the SAP HANA on Azure instance. * @throws IllegalArgumentException thrown if parameters fail the validation - * @throws CloudException thrown if the request is rejected by server + * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void restart(String resourceGroupName, String hanaInstanceName) { @@ -1050,7 +1066,7 @@ public Observable> restartWithServiceResponseAsync(String * @param resourceGroupName Name of the resource group. * @param hanaInstanceName Name of the SAP HANA on Azure instance. * @throws IllegalArgumentException thrown if parameters fail the validation - * @throws CloudException thrown if the request is rejected by server + * @throws ErrorResponseException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginRestart(String resourceGroupName, String hanaInstanceName) { @@ -1122,11 +1138,319 @@ public Observable> call(Response response) { }); } - private ServiceResponse beginRestartDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + private ServiceResponse beginRestartDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) .register(200, new TypeToken() { }.getType()) .register(202, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * The operation to start a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void start(String resourceGroupName, String hanaInstanceName) { + startWithServiceResponseAsync(resourceGroupName, hanaInstanceName).toBlocking().last().body(); + } + + /** + * The operation to start a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture startAsync(String resourceGroupName, String hanaInstanceName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(startWithServiceResponseAsync(resourceGroupName, hanaInstanceName), serviceCallback); + } + + /** + * The operation to start a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable startAsync(String resourceGroupName, String hanaInstanceName) { + return startWithServiceResponseAsync(resourceGroupName, hanaInstanceName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * The operation to start a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> startWithServiceResponseAsync(String resourceGroupName, String hanaInstanceName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (hanaInstanceName == null) { + throw new IllegalArgumentException("Parameter hanaInstanceName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.start(this.client.subscriptionId(), resourceGroupName, hanaInstanceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * The operation to start a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginStart(String resourceGroupName, String hanaInstanceName) { + beginStartWithServiceResponseAsync(resourceGroupName, hanaInstanceName).toBlocking().single().body(); + } + + /** + * The operation to start a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginStartAsync(String resourceGroupName, String hanaInstanceName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginStartWithServiceResponseAsync(resourceGroupName, hanaInstanceName), serviceCallback); + } + + /** + * The operation to start a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginStartAsync(String resourceGroupName, String hanaInstanceName) { + return beginStartWithServiceResponseAsync(resourceGroupName, hanaInstanceName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * The operation to start a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginStartWithServiceResponseAsync(String resourceGroupName, String hanaInstanceName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (hanaInstanceName == null) { + throw new IllegalArgumentException("Parameter hanaInstanceName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginStart(this.client.subscriptionId(), resourceGroupName, hanaInstanceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginStartDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginStartDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * The operation to shutdown a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void shutdown(String resourceGroupName, String hanaInstanceName) { + shutdownWithServiceResponseAsync(resourceGroupName, hanaInstanceName).toBlocking().last().body(); + } + + /** + * The operation to shutdown a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture shutdownAsync(String resourceGroupName, String hanaInstanceName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(shutdownWithServiceResponseAsync(resourceGroupName, hanaInstanceName), serviceCallback); + } + + /** + * The operation to shutdown a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable shutdownAsync(String resourceGroupName, String hanaInstanceName) { + return shutdownWithServiceResponseAsync(resourceGroupName, hanaInstanceName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * The operation to shutdown a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> shutdownWithServiceResponseAsync(String resourceGroupName, String hanaInstanceName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (hanaInstanceName == null) { + throw new IllegalArgumentException("Parameter hanaInstanceName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.shutdown(this.client.subscriptionId(), resourceGroupName, hanaInstanceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * The operation to shutdown a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginShutdown(String resourceGroupName, String hanaInstanceName) { + beginShutdownWithServiceResponseAsync(resourceGroupName, hanaInstanceName).toBlocking().single().body(); + } + + /** + * The operation to shutdown a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginShutdownAsync(String resourceGroupName, String hanaInstanceName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginShutdownWithServiceResponseAsync(resourceGroupName, hanaInstanceName), serviceCallback); + } + + /** + * The operation to shutdown a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginShutdownAsync(String resourceGroupName, String hanaInstanceName) { + return beginShutdownWithServiceResponseAsync(resourceGroupName, hanaInstanceName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * The operation to shutdown a SAP HANA instance. + * + * @param resourceGroupName Name of the resource group. + * @param hanaInstanceName Name of the SAP HANA on Azure instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginShutdownWithServiceResponseAsync(String resourceGroupName, String hanaInstanceName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (hanaInstanceName == null) { + throw new IllegalArgumentException("Parameter hanaInstanceName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginShutdown(this.client.subscriptionId(), resourceGroupName, hanaInstanceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginShutdownDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginShutdownDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) .build(response); } diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaManagementClientImpl.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaManagementClientImpl.java index cca459ef451c3..9bd75711270f7 100644 --- a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaManagementClientImpl.java +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaManagementClientImpl.java @@ -158,6 +158,19 @@ public HanaInstancesInner hanaInstances() { return this.hanaInstances; } + /** + * The SapMonitorsInner object to access its operations. + */ + private SapMonitorsInner sapMonitors; + + /** + * Gets the SapMonitorsInner object to access its operations. + * @return the SapMonitorsInner object. + */ + public SapMonitorsInner sapMonitors() { + return this.sapMonitors; + } + /** * Initializes an instance of HanaManagementClient client. * @@ -195,6 +208,7 @@ protected void initialize() { this.generateClientRequestId = true; this.operations = new OperationsInner(restClient().retrofit(), this); this.hanaInstances = new HanaInstancesInner(restClient().retrofit(), this); + this.sapMonitors = new SapMonitorsInner(restClient().retrofit(), this); this.azureClient = new AzureClient(this); } diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaOnAzureManager.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaOnAzureManager.java index f5492b95bf7e2..1b76c2d2b35f4 100644 --- a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaOnAzureManager.java +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/HanaOnAzureManager.java @@ -18,6 +18,7 @@ import com.microsoft.rest.RestClient; import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.Operations; import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.HanaInstances; +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors; import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl; import com.microsoft.azure.arm.resources.implementation.ManagerCore; @@ -27,6 +28,7 @@ public final class HanaOnAzureManager extends ManagerCore { private Operations operations; private HanaInstances hanaInstances; + private SapMonitors sapMonitors; /** * Get a Configurable instance that can be used to create HanaOnAzureManager with optional configuration. * @@ -94,6 +96,16 @@ public HanaInstances hanaInstances() { return this.hanaInstances; } + /** + * @return Entry point to manage SapMonitors. + */ + public SapMonitors sapMonitors() { + if (this.sapMonitors == null) { + this.sapMonitors = new SapMonitorsImpl(this); + } + return this.sapMonitors; + } + /** * The implementation for Configurable interface. */ diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorImpl.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorImpl.java new file mode 100644 index 0000000000000..9f62f46ebc730 --- /dev/null +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorImpl.java @@ -0,0 +1,118 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.implementation; + +import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitor; +import rx.Observable; +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.HanaProvisioningStatesEnum; + +class SapMonitorImpl extends GroupableResourceCoreImpl implements SapMonitor, SapMonitor.Definition, SapMonitor.Update { + SapMonitorImpl(String name, SapMonitorInner inner, HanaOnAzureManager manager) { + super(name, inner, manager); + } + + @Override + public Observable createResourceAsync() { + SapMonitorsInner client = this.manager().inner().sapMonitors(); + return client.createAsync(this.resourceGroupName(), this.name(), this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + SapMonitorsInner client = this.manager().inner().sapMonitors(); + return client.createAsync(this.resourceGroupName(), this.name(), this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + SapMonitorsInner client = this.manager().inner().sapMonitors(); + return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + + @Override + public String hanaDbName() { + return this.inner().hanaDbName(); + } + + @Override + public String hanaDbPassword() { + return this.inner().hanaDbPassword(); + } + + @Override + public Integer hanaDbSqlPort() { + return this.inner().hanaDbSqlPort(); + } + + @Override + public String hanaDbUsername() { + return this.inner().hanaDbUsername(); + } + + @Override + public String hanaHostname() { + return this.inner().hanaHostname(); + } + + @Override + public String hanaSubnet() { + return this.inner().hanaSubnet(); + } + + @Override + public HanaProvisioningStatesEnum provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public SapMonitorImpl withHanaDbName(String hanaDbName) { + this.inner().withHanaDbName(hanaDbName); + return this; + } + + @Override + public SapMonitorImpl withHanaDbPassword(String hanaDbPassword) { + this.inner().withHanaDbPassword(hanaDbPassword); + return this; + } + + @Override + public SapMonitorImpl withHanaDbSqlPort(Integer hanaDbSqlPort) { + this.inner().withHanaDbSqlPort(hanaDbSqlPort); + return this; + } + + @Override + public SapMonitorImpl withHanaDbUsername(String hanaDbUsername) { + this.inner().withHanaDbUsername(hanaDbUsername); + return this; + } + + @Override + public SapMonitorImpl withHanaHostname(String hanaHostname) { + this.inner().withHanaHostname(hanaHostname); + return this; + } + + @Override + public SapMonitorImpl withHanaSubnet(String hanaSubnet) { + this.inner().withHanaSubnet(hanaSubnet); + return this; + } + +} diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorInner.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorInner.java new file mode 100644 index 0000000000000..bc0d08bbd2215 --- /dev/null +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorInner.java @@ -0,0 +1,196 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.implementation; + +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.HanaProvisioningStatesEnum; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.rest.SkipParentValidation; +import com.microsoft.azure.Resource; + +/** + * SAP monitor info on Azure (ARM properties and SAP monitor properties). + */ +@JsonFlatten +@SkipParentValidation +public class SapMonitorInner extends Resource { + /** + * Specifies the SAP monitor unique ID. + */ + @JsonProperty(value = "properties.hanaSubnet") + private String hanaSubnet; + + /** + * Hostname of the HANA instance. + */ + @JsonProperty(value = "properties.hanaHostname") + private String hanaHostname; + + /** + * Database name of the HANA instance. + */ + @JsonProperty(value = "properties.hanaDbName") + private String hanaDbName; + + /** + * Database port of the HANA instance. + */ + @JsonProperty(value = "properties.hanaDbSqlPort") + private Integer hanaDbSqlPort; + + /** + * Database username of the HANA instance. + */ + @JsonProperty(value = "properties.hanaDbUsername") + private String hanaDbUsername; + + /** + * Database password of the HANA instance. + */ + @JsonProperty(value = "properties.hanaDbPassword") + private String hanaDbPassword; + + /** + * State of provisioning of the HanaInstance. Possible values include: + * 'Accepted', 'Creating', 'Updating', 'Failed', 'Succeeded', 'Deleting', + * 'Migrating'. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private HanaProvisioningStatesEnum provisioningState; + + /** + * Get specifies the SAP monitor unique ID. + * + * @return the hanaSubnet value + */ + public String hanaSubnet() { + return this.hanaSubnet; + } + + /** + * Set specifies the SAP monitor unique ID. + * + * @param hanaSubnet the hanaSubnet value to set + * @return the SapMonitorInner object itself. + */ + public SapMonitorInner withHanaSubnet(String hanaSubnet) { + this.hanaSubnet = hanaSubnet; + return this; + } + + /** + * Get hostname of the HANA instance. + * + * @return the hanaHostname value + */ + public String hanaHostname() { + return this.hanaHostname; + } + + /** + * Set hostname of the HANA instance. + * + * @param hanaHostname the hanaHostname value to set + * @return the SapMonitorInner object itself. + */ + public SapMonitorInner withHanaHostname(String hanaHostname) { + this.hanaHostname = hanaHostname; + return this; + } + + /** + * Get database name of the HANA instance. + * + * @return the hanaDbName value + */ + public String hanaDbName() { + return this.hanaDbName; + } + + /** + * Set database name of the HANA instance. + * + * @param hanaDbName the hanaDbName value to set + * @return the SapMonitorInner object itself. + */ + public SapMonitorInner withHanaDbName(String hanaDbName) { + this.hanaDbName = hanaDbName; + return this; + } + + /** + * Get database port of the HANA instance. + * + * @return the hanaDbSqlPort value + */ + public Integer hanaDbSqlPort() { + return this.hanaDbSqlPort; + } + + /** + * Set database port of the HANA instance. + * + * @param hanaDbSqlPort the hanaDbSqlPort value to set + * @return the SapMonitorInner object itself. + */ + public SapMonitorInner withHanaDbSqlPort(Integer hanaDbSqlPort) { + this.hanaDbSqlPort = hanaDbSqlPort; + return this; + } + + /** + * Get database username of the HANA instance. + * + * @return the hanaDbUsername value + */ + public String hanaDbUsername() { + return this.hanaDbUsername; + } + + /** + * Set database username of the HANA instance. + * + * @param hanaDbUsername the hanaDbUsername value to set + * @return the SapMonitorInner object itself. + */ + public SapMonitorInner withHanaDbUsername(String hanaDbUsername) { + this.hanaDbUsername = hanaDbUsername; + return this; + } + + /** + * Get database password of the HANA instance. + * + * @return the hanaDbPassword value + */ + public String hanaDbPassword() { + return this.hanaDbPassword; + } + + /** + * Set database password of the HANA instance. + * + * @param hanaDbPassword the hanaDbPassword value to set + * @return the SapMonitorInner object itself. + */ + public SapMonitorInner withHanaDbPassword(String hanaDbPassword) { + this.hanaDbPassword = hanaDbPassword; + return this; + } + + /** + * Get state of provisioning of the HanaInstance. Possible values include: 'Accepted', 'Creating', 'Updating', 'Failed', 'Succeeded', 'Deleting', 'Migrating'. + * + * @return the provisioningState value + */ + public HanaProvisioningStatesEnum provisioningState() { + return this.provisioningState; + } + +} diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorsImpl.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorsImpl.java new file mode 100644 index 0000000000000..5d2e60ec7e281 --- /dev/null +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorsImpl.java @@ -0,0 +1,114 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * def + */ + +package com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.implementation; + +import com.microsoft.azure.arm.resources.collection.implementation.GroupableResourcesCoreImpl; +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors; +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitor; +import rx.Observable; +import rx.Completable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import com.microsoft.azure.arm.resources.ResourceUtilsCore; +import com.microsoft.azure.arm.utils.RXMapper; +import rx.functions.Func1; +import com.microsoft.azure.PagedList; +import com.microsoft.azure.Page; + +class SapMonitorsImpl extends GroupableResourcesCoreImpl implements SapMonitors { + protected SapMonitorsImpl(HanaOnAzureManager manager) { + super(manager.inner().sapMonitors(), manager); + } + + @Override + protected Observable getInnerAsync(String resourceGroupName, String name) { + SapMonitorsInner client = this.inner(); + return client.getByResourceGroupAsync(resourceGroupName, name); + } + + @Override + protected Completable deleteInnerAsync(String resourceGroupName, String name) { + SapMonitorsInner client = this.inner(); + return client.deleteAsync(resourceGroupName, name).toCompletable(); + } + + @Override + public Observable deleteByIdsAsync(Collection ids) { + if (ids == null || ids.isEmpty()) { + return Observable.empty(); + } + Collection> observables = new ArrayList<>(); + for (String id : ids) { + final String resourceGroupName = ResourceUtilsCore.groupFromResourceId(id); + final String name = ResourceUtilsCore.nameFromResourceId(id); + Observable o = RXMapper.map(this.inner().deleteAsync(resourceGroupName, name), id); + observables.add(o); + } + return Observable.mergeDelayError(observables); + } + + @Override + public Observable deleteByIdsAsync(String...ids) { + return this.deleteByIdsAsync(new ArrayList(Arrays.asList(ids))); + } + + @Override + public void deleteByIds(Collection ids) { + if (ids != null && !ids.isEmpty()) { + this.deleteByIdsAsync(ids).toBlocking().last(); + } + } + + @Override + public void deleteByIds(String...ids) { + this.deleteByIds(new ArrayList(Arrays.asList(ids))); + } + + @Override + public PagedList list() { + SapMonitorsInner client = this.inner(); + return this.wrapList(client.list()); + } + + @Override + public Observable listAsync() { + SapMonitorsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public SapMonitor call(SapMonitorInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public SapMonitorImpl define(String name) { + return wrapModel(name); + } + + @Override + protected SapMonitorImpl wrapModel(SapMonitorInner inner) { + return new SapMonitorImpl(inner.name(), inner, manager()); + } + + @Override + protected SapMonitorImpl wrapModel(String name) { + return new SapMonitorImpl(name, new SapMonitorInner(), this.manager()); + } + +} diff --git a/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorsInner.java b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorsInner.java new file mode 100644 index 0000000000000..061112bdc85c5 --- /dev/null +++ b/hanaonazure/resource-manager/v2017_11_03_preview/src/main/java/com/microsoft/azure/management/hanaonazure/v2017_11_03_preview/implementation/SapMonitorsInner.java @@ -0,0 +1,947 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.implementation; + +import com.microsoft.azure.arm.collection.InnerSupportsGet; +import com.microsoft.azure.arm.collection.InnerSupportsDelete; +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.ErrorResponseException; +import com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.Tags; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in SapMonitors. + */ +public class SapMonitorsInner implements InnerSupportsGet, InnerSupportsDelete { + /** The Retrofit service to perform REST calls. */ + private SapMonitorsService service; + /** The service client containing this operation class. */ + private HanaManagementClientImpl client; + + /** + * Initializes an instance of SapMonitorsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public SapMonitorsInner(Retrofit retrofit, HanaManagementClientImpl client) { + this.service = retrofit.create(SapMonitorsService.class); + this.client = client; + } + + /** + * The interface defining all the services for SapMonitors to be + * used by Retrofit to perform actually REST calls. + */ + interface SapMonitorsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors list" }) + @GET("subscriptions/{subscriptionId}/providers/Microsoft.HanaOnAzure/sapMonitors") + Observable> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors getByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}") + Observable> getByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("sapMonitorName") String sapMonitorName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors create" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}") + Observable> create(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("sapMonitorName") String sapMonitorName, @Query("api-version") String apiVersion, @Body SapMonitorInner sapMonitorParameter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors beginCreate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}") + Observable> beginCreate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("sapMonitorName") String sapMonitorName, @Query("api-version") String apiVersion, @Body SapMonitorInner sapMonitorParameter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors delete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("sapMonitorName") String sapMonitorName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors beginDelete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("sapMonitorName") String sapMonitorName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors update" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HanaOnAzure/sapMonitors/{sapMonitorName}") + Observable> update(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("sapMonitorName") String sapMonitorName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body Tags tagsParameter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.hanaonazure.v2017_11_03_preview.SapMonitors listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SapMonitorInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SapMonitorInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SapMonitorInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SapMonitorInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets properties of a SAP monitor. + * Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SapMonitorInner object if successful. + */ + public SapMonitorInner getByResourceGroup(String resourceGroupName, String sapMonitorName) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, sapMonitorName).toBlocking().single().body(); + } + + /** + * Gets properties of a SAP monitor. + * Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getByResourceGroupAsync(String resourceGroupName, String sapMonitorName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, sapMonitorName), serviceCallback); + } + + /** + * Gets properties of a SAP monitor. + * Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SapMonitorInner object + */ + public Observable getByResourceGroupAsync(String resourceGroupName, String sapMonitorName) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, sapMonitorName).map(new Func1, SapMonitorInner>() { + @Override + public SapMonitorInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets properties of a SAP monitor. + * Gets properties of a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SapMonitorInner object + */ + public Observable> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String sapMonitorName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sapMonitorName == null) { + throw new IllegalArgumentException("Parameter sapMonitorName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.getByResourceGroup(this.client.subscriptionId(), resourceGroupName, sapMonitorName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getByResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getByResourceGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Creates a SAP monitor. + * Creates a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param sapMonitorParameter Request body representing a SAP Monitor + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SapMonitorInner object if successful. + */ + public SapMonitorInner create(String resourceGroupName, String sapMonitorName, SapMonitorInner sapMonitorParameter) { + return createWithServiceResponseAsync(resourceGroupName, sapMonitorName, sapMonitorParameter).toBlocking().last().body(); + } + + /** + * Creates a SAP monitor. + * Creates a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param sapMonitorParameter Request body representing a SAP Monitor + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String resourceGroupName, String sapMonitorName, SapMonitorInner sapMonitorParameter, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(resourceGroupName, sapMonitorName, sapMonitorParameter), serviceCallback); + } + + /** + * Creates a SAP monitor. + * Creates a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param sapMonitorParameter Request body representing a SAP Monitor + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String resourceGroupName, String sapMonitorName, SapMonitorInner sapMonitorParameter) { + return createWithServiceResponseAsync(resourceGroupName, sapMonitorName, sapMonitorParameter).map(new Func1, SapMonitorInner>() { + @Override + public SapMonitorInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates a SAP monitor. + * Creates a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param sapMonitorParameter Request body representing a SAP Monitor + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String resourceGroupName, String sapMonitorName, SapMonitorInner sapMonitorParameter) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sapMonitorName == null) { + throw new IllegalArgumentException("Parameter sapMonitorName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (sapMonitorParameter == null) { + throw new IllegalArgumentException("Parameter sapMonitorParameter is required and cannot be null."); + } + Validator.validate(sapMonitorParameter); + Observable> observable = service.create(this.client.subscriptionId(), resourceGroupName, sapMonitorName, this.client.apiVersion(), sapMonitorParameter, this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Creates a SAP monitor. + * Creates a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param sapMonitorParameter Request body representing a SAP Monitor + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SapMonitorInner object if successful. + */ + public SapMonitorInner beginCreate(String resourceGroupName, String sapMonitorName, SapMonitorInner sapMonitorParameter) { + return beginCreateWithServiceResponseAsync(resourceGroupName, sapMonitorName, sapMonitorParameter).toBlocking().single().body(); + } + + /** + * Creates a SAP monitor. + * Creates a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param sapMonitorParameter Request body representing a SAP Monitor + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String resourceGroupName, String sapMonitorName, SapMonitorInner sapMonitorParameter, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(resourceGroupName, sapMonitorName, sapMonitorParameter), serviceCallback); + } + + /** + * Creates a SAP monitor. + * Creates a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param sapMonitorParameter Request body representing a SAP Monitor + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SapMonitorInner object + */ + public Observable beginCreateAsync(String resourceGroupName, String sapMonitorName, SapMonitorInner sapMonitorParameter) { + return beginCreateWithServiceResponseAsync(resourceGroupName, sapMonitorName, sapMonitorParameter).map(new Func1, SapMonitorInner>() { + @Override + public SapMonitorInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates a SAP monitor. + * Creates a SAP monitor for the specified subscription, resource group, and resource name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param sapMonitorParameter Request body representing a SAP Monitor + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SapMonitorInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String resourceGroupName, String sapMonitorName, SapMonitorInner sapMonitorParameter) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sapMonitorName == null) { + throw new IllegalArgumentException("Parameter sapMonitorName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (sapMonitorParameter == null) { + throw new IllegalArgumentException("Parameter sapMonitorParameter is required and cannot be null."); + } + Validator.validate(sapMonitorParameter); + return service.beginCreate(this.client.subscriptionId(), resourceGroupName, sapMonitorName, this.client.apiVersion(), sapMonitorParameter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Deletes a SAP monitor. + * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String resourceGroupName, String sapMonitorName) { + deleteWithServiceResponseAsync(resourceGroupName, sapMonitorName).toBlocking().last().body(); + } + + /** + * Deletes a SAP monitor. + * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String resourceGroupName, String sapMonitorName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, sapMonitorName), serviceCallback); + } + + /** + * Deletes a SAP monitor. + * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String resourceGroupName, String sapMonitorName) { + return deleteWithServiceResponseAsync(resourceGroupName, sapMonitorName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes a SAP monitor. + * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String sapMonitorName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sapMonitorName == null) { + throw new IllegalArgumentException("Parameter sapMonitorName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.subscriptionId(), resourceGroupName, sapMonitorName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Deletes a SAP monitor. + * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String resourceGroupName, String sapMonitorName) { + beginDeleteWithServiceResponseAsync(resourceGroupName, sapMonitorName).toBlocking().single().body(); + } + + /** + * Deletes a SAP monitor. + * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String resourceGroupName, String sapMonitorName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, sapMonitorName), serviceCallback); + } + + /** + * Deletes a SAP monitor. + * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String resourceGroupName, String sapMonitorName) { + return beginDeleteWithServiceResponseAsync(resourceGroupName, sapMonitorName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes a SAP monitor. + * Deletes a SAP monitor with the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String resourceGroupName, String sapMonitorName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sapMonitorName == null) { + throw new IllegalArgumentException("Parameter sapMonitorName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.subscriptionId(), resourceGroupName, sapMonitorName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Patches the Tags field of a SAP monitor. + * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SapMonitorInner object if successful. + */ + public SapMonitorInner update(String resourceGroupName, String sapMonitorName) { + return updateWithServiceResponseAsync(resourceGroupName, sapMonitorName).toBlocking().single().body(); + } + + /** + * Patches the Tags field of a SAP monitor. + * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String sapMonitorName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, sapMonitorName), serviceCallback); + } + + /** + * Patches the Tags field of a SAP monitor. + * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SapMonitorInner object + */ + public Observable updateAsync(String resourceGroupName, String sapMonitorName) { + return updateWithServiceResponseAsync(resourceGroupName, sapMonitorName).map(new Func1, SapMonitorInner>() { + @Override + public SapMonitorInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Patches the Tags field of a SAP monitor. + * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SapMonitorInner object + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String sapMonitorName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sapMonitorName == null) { + throw new IllegalArgumentException("Parameter sapMonitorName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final Map tags = null; + Tags tagsParameter = new Tags(); + tagsParameter.withTags(null); + return service.update(this.client.subscriptionId(), resourceGroupName, sapMonitorName, this.client.apiVersion(), this.client.acceptLanguage(), tagsParameter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Patches the Tags field of a SAP monitor. + * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param tags Tags field of the HANA instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SapMonitorInner object if successful. + */ + public SapMonitorInner update(String resourceGroupName, String sapMonitorName, Map tags) { + return updateWithServiceResponseAsync(resourceGroupName, sapMonitorName, tags).toBlocking().single().body(); + } + + /** + * Patches the Tags field of a SAP monitor. + * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param tags Tags field of the HANA instance. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String sapMonitorName, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, sapMonitorName, tags), serviceCallback); + } + + /** + * Patches the Tags field of a SAP monitor. + * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param tags Tags field of the HANA instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SapMonitorInner object + */ + public Observable updateAsync(String resourceGroupName, String sapMonitorName, Map tags) { + return updateWithServiceResponseAsync(resourceGroupName, sapMonitorName, tags).map(new Func1, SapMonitorInner>() { + @Override + public SapMonitorInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Patches the Tags field of a SAP monitor. + * Patches the Tags field of a SAP monitor for the specified subscription, resource group, and monitor name. + * + * @param resourceGroupName Name of the resource group. + * @param sapMonitorName Name of the SAP monitor resource. + * @param tags Tags field of the HANA instance. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SapMonitorInner object + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String sapMonitorName, Map tags) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sapMonitorName == null) { + throw new IllegalArgumentException("Parameter sapMonitorName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(tags); + Tags tagsParameter = new Tags(); + tagsParameter.withTags(tags); + return service.update(this.client.subscriptionId(), resourceGroupName, sapMonitorName, this.client.apiVersion(), this.client.acceptLanguage(), tagsParameter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse updateDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorResponseException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SapMonitorInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SapMonitorInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SapMonitorInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets a list of SAP monitors in the specified subscription. + * Gets a list of SAP monitors in the specified subscription. The operations returns various properties of each SAP monitor. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SapMonitorInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + +} From 808c49df3b3c5b9f1222fdeb59642bb004e1aa65 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Tue, 2 Jul 2019 16:23:48 -0700 Subject: [PATCH 069/147] Resources: generated v2019_05_01 (#4223) * generated v2019_05_01 of resources * updated maven versioning --- .../resource-manager/v2019_05_01/pom.xml | 4 +++- .../v2019_05_01/ExportTemplateRequest.java | 20 +++++++++---------- .../DeploymentOperationsImpl.java | 10 +++++++--- .../implementation/ProvidersImpl.java | 10 +++++++--- .../implementation/ResourceGroupsImpl.java | 10 +++++++--- 5 files changed, 34 insertions(+), 20 deletions(-) diff --git a/resources/resource-manager/v2019_05_01/pom.xml b/resources/resource-manager/v2019_05_01/pom.xml index 5ea7968f30c55..876f64e4c98e6 100644 --- a/resources/resource-manager/v2019_05_01/pom.xml +++ b/resources/resource-manager/v2019_05_01/pom.xml @@ -15,7 +15,7 @@ ../../../pom.management.xml azure-mgmt-resources - 1.0.0-beta + 1.0.0-beta-1 jar Microsoft Azure SDK for Resources Management This package contains Microsoft Resources Management SDK. @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 diff --git a/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/ExportTemplateRequest.java b/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/ExportTemplateRequest.java index 78ff8304a7997..849e59b07cf22 100644 --- a/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/ExportTemplateRequest.java +++ b/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/ExportTemplateRequest.java @@ -16,23 +16,23 @@ */ public class ExportTemplateRequest { /** - * The IDs of the resources. The only supported string currently is '*' - * (all resources). Future updates will support exporting specific - * resources. + * The IDs of the resources to filter the export by. To export all + * resources, supply an array with single entry '*'. */ @JsonProperty(value = "resources") private List resources; /** - * The export template options. Supported values include - * 'IncludeParameterDefaultValue', 'IncludeComments' or - * 'IncludeParameterDefaultValue, IncludeComments. + * The export template options. A CSV-formatted list containing zero or + * more of the following: 'IncludeParameterDefaultValue', + * 'IncludeComments', 'SkipResourceNameParameterization', + * 'SkipAllParameterization'. */ @JsonProperty(value = "options") private String options; /** - * Get the IDs of the resources. The only supported string currently is '*' (all resources). Future updates will support exporting specific resources. + * Get the IDs of the resources to filter the export by. To export all resources, supply an array with single entry '*'. * * @return the resources value */ @@ -41,7 +41,7 @@ public List resources() { } /** - * Set the IDs of the resources. The only supported string currently is '*' (all resources). Future updates will support exporting specific resources. + * Set the IDs of the resources to filter the export by. To export all resources, supply an array with single entry '*'. * * @param resources the resources value to set * @return the ExportTemplateRequest object itself. @@ -52,7 +52,7 @@ public ExportTemplateRequest withResources(List resources) { } /** - * Get the export template options. Supported values include 'IncludeParameterDefaultValue', 'IncludeComments' or 'IncludeParameterDefaultValue, IncludeComments. + * Get the export template options. A CSV-formatted list containing zero or more of the following: 'IncludeParameterDefaultValue', 'IncludeComments', 'SkipResourceNameParameterization', 'SkipAllParameterization'. * * @return the options value */ @@ -61,7 +61,7 @@ public String options() { } /** - * Set the export template options. Supported values include 'IncludeParameterDefaultValue', 'IncludeComments' or 'IncludeParameterDefaultValue, IncludeComments. + * Set the export template options. A CSV-formatted list containing zero or more of the following: 'IncludeParameterDefaultValue', 'IncludeComments', 'SkipResourceNameParameterization', 'SkipAllParameterization'. * * @param options the options value to set * @return the ExportTemplateRequest object itself. diff --git a/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/DeploymentOperationsImpl.java b/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/DeploymentOperationsImpl.java index ee2ba19fa3d05..feff2c66838c1 100644 --- a/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/DeploymentOperationsImpl.java +++ b/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/DeploymentOperationsImpl.java @@ -114,10 +114,14 @@ public DeploymentOperation call(DeploymentOperationInner inner) { public Observable getAtManagementGroupScopeAsync(String groupId, String deploymentName, String operationId) { DeploymentOperationsInner client = this.inner(); return client.getAtManagementGroupScopeAsync(groupId, deploymentName, operationId) - .map(new Func1() { + .flatMap(new Func1>() { @Override - public DeploymentOperation call(DeploymentOperationInner inner) { - return wrapModel(inner); + public Observable call(DeploymentOperationInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((DeploymentOperation)wrapModel(inner)); + } } }); } diff --git a/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/ProvidersImpl.java b/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/ProvidersImpl.java index 60b5f189ceb4e..0d0e9d92facbb 100644 --- a/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/ProvidersImpl.java +++ b/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/ProvidersImpl.java @@ -78,10 +78,14 @@ public Provider call(ProviderInner inner) { public Observable getAsync(String resourceProviderNamespace) { ProvidersInner client = this.inner(); return client.getAsync(resourceProviderNamespace) - .map(new Func1() { + .flatMap(new Func1>() { @Override - public Provider call(ProviderInner inner) { - return wrapModel(inner); + public Observable call(ProviderInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((Provider)wrapModel(inner)); + } } }); } diff --git a/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/ResourceGroupsImpl.java b/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/ResourceGroupsImpl.java index b942e2864c31b..440565aa7dd9f 100644 --- a/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/ResourceGroupsImpl.java +++ b/resources/resource-manager/v2019_05_01/src/main/java/com/microsoft/azure/management/resources/v2019_05_01/implementation/ResourceGroupsImpl.java @@ -84,10 +84,14 @@ public ResourceGroup call(ResourceGroupInner inner) { public Observable getAsync(String resourceGroupName) { ResourceGroupsInner client = this.inner(); return client.getAsync(resourceGroupName) - .map(new Func1() { + .flatMap(new Func1>() { @Override - public ResourceGroup call(ResourceGroupInner inner) { - return wrapModel(inner); + public Observable call(ResourceGroupInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((ResourceGroup)wrapModel(inner)); + } } }); } From 13beaaa9a7a9a41230c4ed0868edc77b521e2007 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Tue, 2 Jul 2019 16:44:13 -0700 Subject: [PATCH 070/147] generated v2019_06_01_preview of containerregistry (#4224) --- .../resource-manager/v2019_06_01_preview/pom.xml | 2 ++ .../v2019_06_01_preview/implementation/RunsImpl.java | 10 +++++++--- .../v2019_06_01_preview/implementation/TasksImpl.java | 10 +++++++--- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/containerregistry/resource-manager/v2019_06_01_preview/pom.xml b/containerregistry/resource-manager/v2019_06_01_preview/pom.xml index 4e2f42f32b290..3c7e9344faaf4 100644 --- a/containerregistry/resource-manager/v2019_06_01_preview/pom.xml +++ b/containerregistry/resource-manager/v2019_06_01_preview/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 diff --git a/containerregistry/resource-manager/v2019_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2019_06_01_preview/implementation/RunsImpl.java b/containerregistry/resource-manager/v2019_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2019_06_01_preview/implementation/RunsImpl.java index be070d16d75ad..48890a2610864 100644 --- a/containerregistry/resource-manager/v2019_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2019_06_01_preview/implementation/RunsImpl.java +++ b/containerregistry/resource-manager/v2019_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2019_06_01_preview/implementation/RunsImpl.java @@ -74,10 +74,14 @@ public Run call(RunInner inner) { public Observable getAsync(String resourceGroupName, String registryName, String runId) { RunsInner client = this.inner(); return client.getAsync(resourceGroupName, registryName, runId) - .map(new Func1() { + .flatMap(new Func1>() { @Override - public Run call(RunInner inner) { - return wrapModel(inner); + public Observable call(RunInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((Run)wrapModel(inner)); + } } }); } diff --git a/containerregistry/resource-manager/v2019_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2019_06_01_preview/implementation/TasksImpl.java b/containerregistry/resource-manager/v2019_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2019_06_01_preview/implementation/TasksImpl.java index d8ca2fd2f9a23..10a2d87819955 100644 --- a/containerregistry/resource-manager/v2019_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2019_06_01_preview/implementation/TasksImpl.java +++ b/containerregistry/resource-manager/v2019_06_01_preview/src/main/java/com/microsoft/azure/management/containerregistry/v2019_06_01_preview/implementation/TasksImpl.java @@ -76,10 +76,14 @@ public Task call(TaskInner inner) { public Observable getAsync(String resourceGroupName, String registryName, String taskName) { TasksInner client = this.inner(); return client.getAsync(resourceGroupName, registryName, taskName) - .map(new Func1() { + .flatMap(new Func1>() { @Override - public Task call(TaskInner inner) { - return wrapModel(inner); + public Observable call(TaskInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((Task)wrapModel(inner)); + } } }); } From c6fdb6ed987e40b8585c7629fcb819e0cdfa4fc0 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Tue, 2 Jul 2019 16:46:14 -0700 Subject: [PATCH 071/147] update azure-arm-client-runtime test jar dependency (#4233) --- .../resource-manager/v2015_11_01_preview/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/operationsmanagement/resource-manager/v2015_11_01_preview/pom.xml b/operationsmanagement/resource-manager/v2015_11_01_preview/pom.xml index ba38371ea9207..7b030a5cc6ac1 100644 --- a/operationsmanagement/resource-manager/v2015_11_01_preview/pom.xml +++ b/operationsmanagement/resource-manager/v2015_11_01_preview/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 8c0ec1b1bcb7a0ea6f00e0d87ccc4025464a5518 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Tue, 2 Jul 2019 16:47:04 -0700 Subject: [PATCH 072/147] update azure-arm-client-runtime test jar dependency (#4231) --- compute/resource-manager/v2018_09_30/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/compute/resource-manager/v2018_09_30/pom.xml b/compute/resource-manager/v2018_09_30/pom.xml index 2da22f6cf4958..cd4e19cb2711d 100644 --- a/compute/resource-manager/v2018_09_30/pom.xml +++ b/compute/resource-manager/v2018_09_30/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 848429ed5581d755fcb0a6af6627d5b9658b785e Mon Sep 17 00:00:00 2001 From: Yaohai Zheng Date: Wed, 3 Jul 2019 10:23:01 +0800 Subject: [PATCH 073/147] SQL VirtualMachine: generated v2017_03_01_preview. (#4245) --- api-specs.json | 4 + .../v2017_03_01_preview/pom.xml | 135 ++ ...dditionalFeaturesServerConfigurations.java | 43 + .../AutoBackupSettings.java | 332 ++++ .../AutoPatchingSettings.java | 122 ++ .../AvailabilityGroupListener.java | 210 +++ .../AvailabilityGroupListeners.java | 53 + .../BackupScheduleType.java | 41 + .../ClusterConfiguration.java | 38 + .../ClusterManagerType.java | 38 + .../v2017_03_01_preview/ConnectivityType.java | 44 + .../v2017_03_01_preview/DayOfWeek.java | 68 + .../DiskConfigurationType.java | 44 + .../FullBackupFrequencyType.java | 41 + .../v2017_03_01_preview/IdentityType.java | 38 + .../KeyVaultCredentialSettings.java | 148 ++ .../LoadBalancerConfiguration.java | 149 ++ .../v2017_03_01_preview/Operation.java | 41 + .../v2017_03_01_preview/OperationDisplay.java | 78 + .../v2017_03_01_preview/OperationOrigin.java | 41 + .../v2017_03_01_preview/Operations.java | 27 + .../v2017_03_01_preview/PrivateIPAddress.java | 69 + .../v2017_03_01_preview/ResourceIdentity.java | 76 + .../v2017_03_01_preview/ScaleType.java | 38 + ...erverConfigurationsManagementSettings.java | 121 ++ .../SqlConnectivityUpdateSettings.java | 122 ++ .../v2017_03_01_preview/SqlImageSku.java | 50 + .../SqlManagementMode.java | 44 + .../SqlServerLicenseType.java | 41 + .../SqlStorageUpdateSettings.java | 96 ++ .../SqlVirtualMachine.java | 421 +++++ .../SqlVirtualMachineGroup.java | 175 +++ .../SqlVirtualMachineGroupUpdate.java | 44 + .../SqlVirtualMachineGroups.java | 25 + .../SqlVirtualMachineUpdate.java | 44 + .../SqlVirtualMachines.java | 25 + .../SqlVmGroupImageSku.java | 41 + .../v2017_03_01_preview/SqlWorkloadType.java | 44 + .../SqlWorkloadTypeUpdateSettings.java | 44 + .../WsfcDomainCredentials.java | 96 ++ .../WsfcDomainProfile.java | 229 +++ .../AvailabilityGroupListenerImpl.java | 145 ++ .../AvailabilityGroupListenerInner.java | 141 ++ .../AvailabilityGroupListenersImpl.java | 85 + .../AvailabilityGroupListenersInner.java | 776 ++++++++++ .../implementation/IdParsingUtils.java | 57 + .../implementation/OperationImpl.java | 49 + .../implementation/OperationInner.java | 82 + .../implementation/OperationsImpl.java | 49 + .../implementation/OperationsInner.java | 283 ++++ .../implementation/PageImpl.java | 75 + .../SqlVirtualMachineGroupImpl.java | 104 ++ .../SqlVirtualMachineGroupInner.java | 165 ++ .../SqlVirtualMachineGroupsImpl.java | 138 ++ .../SqlVirtualMachineGroupsInner.java | 1295 ++++++++++++++++ .../implementation/SqlVirtualMachineImpl.java | 192 +++ .../SqlVirtualMachineInner.java | 362 +++++ ...SqlVirtualMachineManagementClientImpl.java | 238 +++ .../SqlVirtualMachineManager.java | 135 ++ .../SqlVirtualMachinesImpl.java | 138 ++ .../SqlVirtualMachinesInner.java | 1379 +++++++++++++++++ .../implementation/package-info.java | 11 + .../v2017_03_01_preview/package-info.java | 11 + 63 files changed, 9490 insertions(+) create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/pom.xml create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AdditionalFeaturesServerConfigurations.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AutoBackupSettings.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AutoPatchingSettings.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AvailabilityGroupListener.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AvailabilityGroupListeners.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/BackupScheduleType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ClusterConfiguration.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ClusterManagerType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ConnectivityType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/DayOfWeek.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/DiskConfigurationType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/FullBackupFrequencyType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/IdentityType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/KeyVaultCredentialSettings.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/LoadBalancerConfiguration.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/Operation.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/OperationDisplay.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/OperationOrigin.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/Operations.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/PrivateIPAddress.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ResourceIdentity.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ScaleType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ServerConfigurationsManagementSettings.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlConnectivityUpdateSettings.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlImageSku.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlManagementMode.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlServerLicenseType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlStorageUpdateSettings.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachine.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroup.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroupUpdate.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroups.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineUpdate.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachines.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVmGroupImageSku.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlWorkloadType.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlWorkloadTypeUpdateSettings.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/WsfcDomainCredentials.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/WsfcDomainProfile.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenerImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenerInner.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenersImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenersInner.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/IdParsingUtils.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationInner.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationsImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationsInner.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/PageImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupInner.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupsImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupsInner.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineInner.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineManagementClientImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineManager.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachinesImpl.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachinesInner.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/package-info.java create mode 100644 sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/package-info.java diff --git a/api-specs.json b/api-specs.json index 3f5745dc8f28c..901c9b31536e8 100644 --- a/api-specs.json +++ b/api-specs.json @@ -256,6 +256,10 @@ "source": "specification/sql/resource-manager/readme.md", "args": "--multiapi --fluent" }, + "sqlvirtualmachine/resource-manager": { + "source": "specification/sqlvirtualmachine/resource-manager/readme.md", + "args": "--multiapi --fluent" + }, "storage/resource-manager": { "source": "specification/storage/resource-manager/readme.md", "args": "--multiapi --fluent" diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/pom.xml b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/pom.xml new file mode 100644 index 0000000000000..b1ca95bfd516b --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + com.microsoft.azure.sqlvirtualmachine.v2017_03_01_preview + + com.microsoft.azure + azure-arm-parent + 1.1.0 + ../../../pom.management.xml + + azure-mgmt-sqlvirtualmachine + 1.0.0-beta + jar + Microsoft Azure SDK for SqlVirtualMachine Management + This package contains Microsoft SqlVirtualMachine Management SDK. + https://github.com/Azure/azure-sdk-for-java + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + UTF-8 + + + + + microsoft + Microsoft + + + + + com.microsoft.azure + azure-client-runtime + + + com.microsoft.azure + azure-arm-client-runtime + + + junit + junit + test + + + com.microsoft.azure + azure-client-authentication + test + + + com.microsoft.azure + azure-mgmt-resources + test + + + com.microsoft.azure + azure-arm-client-runtime + test-jar + test + + 1.6.5 + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + true + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + com.microsoft.azure.management.apigeneration.LangDefinitionProcessor + + + true + true + + true + true + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.search + + + /** +
* Copyright (c) Microsoft Corporation. All rights reserved. +
* Licensed under the MIT License. See License.txt in the project root for +
* license information. +
*/ + ]]> +
+
+
+
+
+
diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AdditionalFeaturesServerConfigurations.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AdditionalFeaturesServerConfigurations.java new file mode 100644 index 0000000000000..5bac163dcfe0a --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AdditionalFeaturesServerConfigurations.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Additional SQL Server feature settings. + */ +public class AdditionalFeaturesServerConfigurations { + /** + * Enable or disable R services (SQL 2016 onwards). + */ + @JsonProperty(value = "isRServicesEnabled") + private Boolean isRServicesEnabled; + + /** + * Get enable or disable R services (SQL 2016 onwards). + * + * @return the isRServicesEnabled value + */ + public Boolean isRServicesEnabled() { + return this.isRServicesEnabled; + } + + /** + * Set enable or disable R services (SQL 2016 onwards). + * + * @param isRServicesEnabled the isRServicesEnabled value to set + * @return the AdditionalFeaturesServerConfigurations object itself. + */ + public AdditionalFeaturesServerConfigurations withIsRServicesEnabled(Boolean isRServicesEnabled) { + this.isRServicesEnabled = isRServicesEnabled; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AutoBackupSettings.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AutoBackupSettings.java new file mode 100644 index 0000000000000..6789a508fd0ab --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AutoBackupSettings.java @@ -0,0 +1,332 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Configure backups for databases in your SQL virtual machine. + */ +public class AutoBackupSettings { + /** + * Enable or disable autobackup on SQL virtual machine. + */ + @JsonProperty(value = "enable") + private Boolean enable; + + /** + * Enable or disable encryption for backup on SQL virtual machine. + */ + @JsonProperty(value = "enableEncryption") + private Boolean enableEncryption; + + /** + * Retention period of backup: 1-30 days. + */ + @JsonProperty(value = "retentionPeriod") + private Integer retentionPeriod; + + /** + * Storage account url where backup will be taken to. + */ + @JsonProperty(value = "storageAccountUrl") + private String storageAccountUrl; + + /** + * Storage account key where backup will be taken to. + */ + @JsonProperty(value = "storageAccessKey") + private String storageAccessKey; + + /** + * Password for encryption on backup. + */ + @JsonProperty(value = "password") + private String password; + + /** + * Include or exclude system databases from auto backup. + */ + @JsonProperty(value = "backupSystemDbs") + private Boolean backupSystemDbs; + + /** + * Backup schedule type. Possible values include: 'Manual', 'Automated'. + */ + @JsonProperty(value = "backupScheduleType") + private BackupScheduleType backupScheduleType; + + /** + * Frequency of full backups. In both cases, full backups begin during the + * next scheduled time window. Possible values include: 'Daily', 'Weekly'. + */ + @JsonProperty(value = "fullBackupFrequency") + private FullBackupFrequencyType fullBackupFrequency; + + /** + * Start time of a given day during which full backups can take place. 0-23 + * hours. + */ + @JsonProperty(value = "fullBackupStartTime") + private Integer fullBackupStartTime; + + /** + * Duration of the time window of a given day during which full backups can + * take place. 1-23 hours. + */ + @JsonProperty(value = "fullBackupWindowHours") + private Integer fullBackupWindowHours; + + /** + * Frequency of log backups. 5-60 minutes. + */ + @JsonProperty(value = "logBackupFrequency") + private Integer logBackupFrequency; + + /** + * Get enable or disable autobackup on SQL virtual machine. + * + * @return the enable value + */ + public Boolean enable() { + return this.enable; + } + + /** + * Set enable or disable autobackup on SQL virtual machine. + * + * @param enable the enable value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withEnable(Boolean enable) { + this.enable = enable; + return this; + } + + /** + * Get enable or disable encryption for backup on SQL virtual machine. + * + * @return the enableEncryption value + */ + public Boolean enableEncryption() { + return this.enableEncryption; + } + + /** + * Set enable or disable encryption for backup on SQL virtual machine. + * + * @param enableEncryption the enableEncryption value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withEnableEncryption(Boolean enableEncryption) { + this.enableEncryption = enableEncryption; + return this; + } + + /** + * Get retention period of backup: 1-30 days. + * + * @return the retentionPeriod value + */ + public Integer retentionPeriod() { + return this.retentionPeriod; + } + + /** + * Set retention period of backup: 1-30 days. + * + * @param retentionPeriod the retentionPeriod value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withRetentionPeriod(Integer retentionPeriod) { + this.retentionPeriod = retentionPeriod; + return this; + } + + /** + * Get storage account url where backup will be taken to. + * + * @return the storageAccountUrl value + */ + public String storageAccountUrl() { + return this.storageAccountUrl; + } + + /** + * Set storage account url where backup will be taken to. + * + * @param storageAccountUrl the storageAccountUrl value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withStorageAccountUrl(String storageAccountUrl) { + this.storageAccountUrl = storageAccountUrl; + return this; + } + + /** + * Get storage account key where backup will be taken to. + * + * @return the storageAccessKey value + */ + public String storageAccessKey() { + return this.storageAccessKey; + } + + /** + * Set storage account key where backup will be taken to. + * + * @param storageAccessKey the storageAccessKey value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withStorageAccessKey(String storageAccessKey) { + this.storageAccessKey = storageAccessKey; + return this; + } + + /** + * Get password for encryption on backup. + * + * @return the password value + */ + public String password() { + return this.password; + } + + /** + * Set password for encryption on backup. + * + * @param password the password value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withPassword(String password) { + this.password = password; + return this; + } + + /** + * Get include or exclude system databases from auto backup. + * + * @return the backupSystemDbs value + */ + public Boolean backupSystemDbs() { + return this.backupSystemDbs; + } + + /** + * Set include or exclude system databases from auto backup. + * + * @param backupSystemDbs the backupSystemDbs value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withBackupSystemDbs(Boolean backupSystemDbs) { + this.backupSystemDbs = backupSystemDbs; + return this; + } + + /** + * Get backup schedule type. Possible values include: 'Manual', 'Automated'. + * + * @return the backupScheduleType value + */ + public BackupScheduleType backupScheduleType() { + return this.backupScheduleType; + } + + /** + * Set backup schedule type. Possible values include: 'Manual', 'Automated'. + * + * @param backupScheduleType the backupScheduleType value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withBackupScheduleType(BackupScheduleType backupScheduleType) { + this.backupScheduleType = backupScheduleType; + return this; + } + + /** + * Get frequency of full backups. In both cases, full backups begin during the next scheduled time window. Possible values include: 'Daily', 'Weekly'. + * + * @return the fullBackupFrequency value + */ + public FullBackupFrequencyType fullBackupFrequency() { + return this.fullBackupFrequency; + } + + /** + * Set frequency of full backups. In both cases, full backups begin during the next scheduled time window. Possible values include: 'Daily', 'Weekly'. + * + * @param fullBackupFrequency the fullBackupFrequency value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withFullBackupFrequency(FullBackupFrequencyType fullBackupFrequency) { + this.fullBackupFrequency = fullBackupFrequency; + return this; + } + + /** + * Get start time of a given day during which full backups can take place. 0-23 hours. + * + * @return the fullBackupStartTime value + */ + public Integer fullBackupStartTime() { + return this.fullBackupStartTime; + } + + /** + * Set start time of a given day during which full backups can take place. 0-23 hours. + * + * @param fullBackupStartTime the fullBackupStartTime value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withFullBackupStartTime(Integer fullBackupStartTime) { + this.fullBackupStartTime = fullBackupStartTime; + return this; + } + + /** + * Get duration of the time window of a given day during which full backups can take place. 1-23 hours. + * + * @return the fullBackupWindowHours value + */ + public Integer fullBackupWindowHours() { + return this.fullBackupWindowHours; + } + + /** + * Set duration of the time window of a given day during which full backups can take place. 1-23 hours. + * + * @param fullBackupWindowHours the fullBackupWindowHours value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withFullBackupWindowHours(Integer fullBackupWindowHours) { + this.fullBackupWindowHours = fullBackupWindowHours; + return this; + } + + /** + * Get frequency of log backups. 5-60 minutes. + * + * @return the logBackupFrequency value + */ + public Integer logBackupFrequency() { + return this.logBackupFrequency; + } + + /** + * Set frequency of log backups. 5-60 minutes. + * + * @param logBackupFrequency the logBackupFrequency value to set + * @return the AutoBackupSettings object itself. + */ + public AutoBackupSettings withLogBackupFrequency(Integer logBackupFrequency) { + this.logBackupFrequency = logBackupFrequency; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AutoPatchingSettings.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AutoPatchingSettings.java new file mode 100644 index 0000000000000..7192c1ba5f103 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AutoPatchingSettings.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Set a patching window during which Windows and SQL patches will be applied. + */ +public class AutoPatchingSettings { + /** + * Enable or disable autopatching on SQL virtual machine. + */ + @JsonProperty(value = "enable") + private Boolean enable; + + /** + * Day of week to apply the patch on. Possible values include: 'Monday', + * 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'. + */ + @JsonProperty(value = "dayOfWeek") + private DayOfWeek dayOfWeek; + + /** + * Hour of the day when patching is initiated. Local VM time. + */ + @JsonProperty(value = "maintenanceWindowStartingHour") + private Integer maintenanceWindowStartingHour; + + /** + * Duration of patching. + */ + @JsonProperty(value = "maintenanceWindowDuration") + private Integer maintenanceWindowDuration; + + /** + * Get enable or disable autopatching on SQL virtual machine. + * + * @return the enable value + */ + public Boolean enable() { + return this.enable; + } + + /** + * Set enable or disable autopatching on SQL virtual machine. + * + * @param enable the enable value to set + * @return the AutoPatchingSettings object itself. + */ + public AutoPatchingSettings withEnable(Boolean enable) { + this.enable = enable; + return this; + } + + /** + * Get day of week to apply the patch on. Possible values include: 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'. + * + * @return the dayOfWeek value + */ + public DayOfWeek dayOfWeek() { + return this.dayOfWeek; + } + + /** + * Set day of week to apply the patch on. Possible values include: 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'. + * + * @param dayOfWeek the dayOfWeek value to set + * @return the AutoPatchingSettings object itself. + */ + public AutoPatchingSettings withDayOfWeek(DayOfWeek dayOfWeek) { + this.dayOfWeek = dayOfWeek; + return this; + } + + /** + * Get hour of the day when patching is initiated. Local VM time. + * + * @return the maintenanceWindowStartingHour value + */ + public Integer maintenanceWindowStartingHour() { + return this.maintenanceWindowStartingHour; + } + + /** + * Set hour of the day when patching is initiated. Local VM time. + * + * @param maintenanceWindowStartingHour the maintenanceWindowStartingHour value to set + * @return the AutoPatchingSettings object itself. + */ + public AutoPatchingSettings withMaintenanceWindowStartingHour(Integer maintenanceWindowStartingHour) { + this.maintenanceWindowStartingHour = maintenanceWindowStartingHour; + return this; + } + + /** + * Get duration of patching. + * + * @return the maintenanceWindowDuration value + */ + public Integer maintenanceWindowDuration() { + return this.maintenanceWindowDuration; + } + + /** + * Set duration of patching. + * + * @param maintenanceWindowDuration the maintenanceWindowDuration value to set + * @return the AutoPatchingSettings object itself. + */ + public AutoPatchingSettings withMaintenanceWindowDuration(Integer maintenanceWindowDuration) { + this.maintenanceWindowDuration = maintenanceWindowDuration; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AvailabilityGroupListener.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AvailabilityGroupListener.java new file mode 100644 index 0000000000000..ab53efa1e0d77 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AvailabilityGroupListener.java @@ -0,0 +1,210 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.AvailabilityGroupListenerInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.SqlVirtualMachineManager; +import java.util.List; + +/** + * Type representing AvailabilityGroupListener. + */ +public interface AvailabilityGroupListener extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the availabilityGroupName value. + */ + String availabilityGroupName(); + + /** + * @return the createDefaultAvailabilityGroupIfNotExist value. + */ + Boolean createDefaultAvailabilityGroupIfNotExist(); + + /** + * @return the id value. + */ + String id(); + + /** + * @return the loadBalancerConfigurations value. + */ + List loadBalancerConfigurations(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the port value. + */ + Integer port(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the AvailabilityGroupListener definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithSqlVirtualMachineGroup, DefinitionStages.WithCreate { + } + + /** + * Grouping of AvailabilityGroupListener definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a AvailabilityGroupListener definition. + */ + interface Blank extends WithSqlVirtualMachineGroup { + } + + /** + * The stage of the availabilitygrouplistener definition allowing to specify SqlVirtualMachineGroup. + */ + interface WithSqlVirtualMachineGroup { + /** + * Specifies resourceGroupName, sqlVirtualMachineGroupName. + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group + * @return the next definition stage + */ + WithCreate withExistingSqlVirtualMachineGroup(String resourceGroupName, String sqlVirtualMachineGroupName); + } + + /** + * The stage of the availabilitygrouplistener definition allowing to specify AvailabilityGroupName. + */ + interface WithAvailabilityGroupName { + /** + * Specifies availabilityGroupName. + * @param availabilityGroupName Name of the availability group + * @return the next definition stage + */ + WithCreate withAvailabilityGroupName(String availabilityGroupName); + } + + /** + * The stage of the availabilitygrouplistener definition allowing to specify CreateDefaultAvailabilityGroupIfNotExist. + */ + interface WithCreateDefaultAvailabilityGroupIfNotExist { + /** + * Specifies createDefaultAvailabilityGroupIfNotExist. + * @param createDefaultAvailabilityGroupIfNotExist Create a default availability group if it does not exist + * @return the next definition stage + */ + WithCreate withCreateDefaultAvailabilityGroupIfNotExist(Boolean createDefaultAvailabilityGroupIfNotExist); + } + + /** + * The stage of the availabilitygrouplistener definition allowing to specify LoadBalancerConfigurations. + */ + interface WithLoadBalancerConfigurations { + /** + * Specifies loadBalancerConfigurations. + * @param loadBalancerConfigurations List of load balancer configurations for an availability group listener + * @return the next definition stage + */ + WithCreate withLoadBalancerConfigurations(List loadBalancerConfigurations); + } + + /** + * The stage of the availabilitygrouplistener definition allowing to specify Port. + */ + interface WithPort { + /** + * Specifies port. + * @param port Listener port + * @return the next definition stage + */ + WithCreate withPort(Integer port); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, DefinitionStages.WithAvailabilityGroupName, DefinitionStages.WithCreateDefaultAvailabilityGroupIfNotExist, DefinitionStages.WithLoadBalancerConfigurations, DefinitionStages.WithPort { + } + } + /** + * The template for a AvailabilityGroupListener update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithAvailabilityGroupName, UpdateStages.WithCreateDefaultAvailabilityGroupIfNotExist, UpdateStages.WithLoadBalancerConfigurations, UpdateStages.WithPort { + } + + /** + * Grouping of AvailabilityGroupListener update stages. + */ + interface UpdateStages { + /** + * The stage of the availabilitygrouplistener update allowing to specify AvailabilityGroupName. + */ + interface WithAvailabilityGroupName { + /** + * Specifies availabilityGroupName. + * @param availabilityGroupName Name of the availability group + * @return the next update stage + */ + Update withAvailabilityGroupName(String availabilityGroupName); + } + + /** + * The stage of the availabilitygrouplistener update allowing to specify CreateDefaultAvailabilityGroupIfNotExist. + */ + interface WithCreateDefaultAvailabilityGroupIfNotExist { + /** + * Specifies createDefaultAvailabilityGroupIfNotExist. + * @param createDefaultAvailabilityGroupIfNotExist Create a default availability group if it does not exist + * @return the next update stage + */ + Update withCreateDefaultAvailabilityGroupIfNotExist(Boolean createDefaultAvailabilityGroupIfNotExist); + } + + /** + * The stage of the availabilitygrouplistener update allowing to specify LoadBalancerConfigurations. + */ + interface WithLoadBalancerConfigurations { + /** + * Specifies loadBalancerConfigurations. + * @param loadBalancerConfigurations List of load balancer configurations for an availability group listener + * @return the next update stage + */ + Update withLoadBalancerConfigurations(List loadBalancerConfigurations); + } + + /** + * The stage of the availabilitygrouplistener update allowing to specify Port. + */ + interface WithPort { + /** + * Specifies port. + * @param port Listener port + * @return the next update stage + */ + Update withPort(Integer port); + } + + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AvailabilityGroupListeners.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AvailabilityGroupListeners.java new file mode 100644 index 0000000000000..f381e4e983125 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/AvailabilityGroupListeners.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.AvailabilityGroupListenersInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing AvailabilityGroupListeners. + */ +public interface AvailabilityGroupListeners extends SupportsCreating, HasInner { + /** + * Gets an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName); + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByGroupAsync(final String resourceGroupName, final String sqlVirtualMachineGroupName); + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName); + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/BackupScheduleType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/BackupScheduleType.java new file mode 100644 index 0000000000000..5b82c5db17fe2 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/BackupScheduleType.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for BackupScheduleType. + */ +public final class BackupScheduleType extends ExpandableStringEnum { + /** Static value Manual for BackupScheduleType. */ + public static final BackupScheduleType MANUAL = fromString("Manual"); + + /** Static value Automated for BackupScheduleType. */ + public static final BackupScheduleType AUTOMATED = fromString("Automated"); + + /** + * Creates or finds a BackupScheduleType from its string representation. + * @param name a name to look for + * @return the corresponding BackupScheduleType + */ + @JsonCreator + public static BackupScheduleType fromString(String name) { + return fromString(name, BackupScheduleType.class); + } + + /** + * @return known BackupScheduleType values + */ + public static Collection values() { + return values(BackupScheduleType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ClusterConfiguration.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ClusterConfiguration.java new file mode 100644 index 0000000000000..4da03ae83b67c --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ClusterConfiguration.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for ClusterConfiguration. + */ +public final class ClusterConfiguration extends ExpandableStringEnum { + /** Static value Domainful for ClusterConfiguration. */ + public static final ClusterConfiguration DOMAINFUL = fromString("Domainful"); + + /** + * Creates or finds a ClusterConfiguration from its string representation. + * @param name a name to look for + * @return the corresponding ClusterConfiguration + */ + @JsonCreator + public static ClusterConfiguration fromString(String name) { + return fromString(name, ClusterConfiguration.class); + } + + /** + * @return known ClusterConfiguration values + */ + public static Collection values() { + return values(ClusterConfiguration.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ClusterManagerType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ClusterManagerType.java new file mode 100644 index 0000000000000..5ff3a8174728c --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ClusterManagerType.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for ClusterManagerType. + */ +public final class ClusterManagerType extends ExpandableStringEnum { + /** Static value WSFC for ClusterManagerType. */ + public static final ClusterManagerType WSFC = fromString("WSFC"); + + /** + * Creates or finds a ClusterManagerType from its string representation. + * @param name a name to look for + * @return the corresponding ClusterManagerType + */ + @JsonCreator + public static ClusterManagerType fromString(String name) { + return fromString(name, ClusterManagerType.class); + } + + /** + * @return known ClusterManagerType values + */ + public static Collection values() { + return values(ClusterManagerType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ConnectivityType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ConnectivityType.java new file mode 100644 index 0000000000000..e3bb4ae04b79b --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ConnectivityType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for ConnectivityType. + */ +public final class ConnectivityType extends ExpandableStringEnum { + /** Static value LOCAL for ConnectivityType. */ + public static final ConnectivityType LOCAL = fromString("LOCAL"); + + /** Static value PRIVATE for ConnectivityType. */ + public static final ConnectivityType PRIVATE = fromString("PRIVATE"); + + /** Static value PUBLIC for ConnectivityType. */ + public static final ConnectivityType PUBLIC = fromString("PUBLIC"); + + /** + * Creates or finds a ConnectivityType from its string representation. + * @param name a name to look for + * @return the corresponding ConnectivityType + */ + @JsonCreator + public static ConnectivityType fromString(String name) { + return fromString(name, ConnectivityType.class); + } + + /** + * @return known ConnectivityType values + */ + public static Collection values() { + return values(ConnectivityType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/DayOfWeek.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/DayOfWeek.java new file mode 100644 index 0000000000000..38ef71f2d5e54 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/DayOfWeek.java @@ -0,0 +1,68 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for DayOfWeek. + */ +public enum DayOfWeek { + /** Enum value Monday. */ + MONDAY("Monday"), + + /** Enum value Tuesday. */ + TUESDAY("Tuesday"), + + /** Enum value Wednesday. */ + WEDNESDAY("Wednesday"), + + /** Enum value Thursday. */ + THURSDAY("Thursday"), + + /** Enum value Friday. */ + FRIDAY("Friday"), + + /** Enum value Saturday. */ + SATURDAY("Saturday"), + + /** Enum value Sunday. */ + SUNDAY("Sunday"); + + /** The actual serialized value for a DayOfWeek instance. */ + private String value; + + DayOfWeek(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a DayOfWeek instance. + * + * @param value the serialized value to parse. + * @return the parsed DayOfWeek object, or null if unable to parse. + */ + @JsonCreator + public static DayOfWeek fromString(String value) { + DayOfWeek[] items = DayOfWeek.values(); + for (DayOfWeek item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/DiskConfigurationType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/DiskConfigurationType.java new file mode 100644 index 0000000000000..49e844b68c8dd --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/DiskConfigurationType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for DiskConfigurationType. + */ +public final class DiskConfigurationType extends ExpandableStringEnum { + /** Static value NEW for DiskConfigurationType. */ + public static final DiskConfigurationType NEW = fromString("NEW"); + + /** Static value EXTEND for DiskConfigurationType. */ + public static final DiskConfigurationType EXTEND = fromString("EXTEND"); + + /** Static value ADD for DiskConfigurationType. */ + public static final DiskConfigurationType ADD = fromString("ADD"); + + /** + * Creates or finds a DiskConfigurationType from its string representation. + * @param name a name to look for + * @return the corresponding DiskConfigurationType + */ + @JsonCreator + public static DiskConfigurationType fromString(String name) { + return fromString(name, DiskConfigurationType.class); + } + + /** + * @return known DiskConfigurationType values + */ + public static Collection values() { + return values(DiskConfigurationType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/FullBackupFrequencyType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/FullBackupFrequencyType.java new file mode 100644 index 0000000000000..b6165e6da9ac1 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/FullBackupFrequencyType.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for FullBackupFrequencyType. + */ +public final class FullBackupFrequencyType extends ExpandableStringEnum { + /** Static value Daily for FullBackupFrequencyType. */ + public static final FullBackupFrequencyType DAILY = fromString("Daily"); + + /** Static value Weekly for FullBackupFrequencyType. */ + public static final FullBackupFrequencyType WEEKLY = fromString("Weekly"); + + /** + * Creates or finds a FullBackupFrequencyType from its string representation. + * @param name a name to look for + * @return the corresponding FullBackupFrequencyType + */ + @JsonCreator + public static FullBackupFrequencyType fromString(String name) { + return fromString(name, FullBackupFrequencyType.class); + } + + /** + * @return known FullBackupFrequencyType values + */ + public static Collection values() { + return values(FullBackupFrequencyType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/IdentityType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/IdentityType.java new file mode 100644 index 0000000000000..3fcf662038824 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/IdentityType.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for IdentityType. + */ +public final class IdentityType extends ExpandableStringEnum { + /** Static value SystemAssigned for IdentityType. */ + public static final IdentityType SYSTEM_ASSIGNED = fromString("SystemAssigned"); + + /** + * Creates or finds a IdentityType from its string representation. + * @param name a name to look for + * @return the corresponding IdentityType + */ + @JsonCreator + public static IdentityType fromString(String name) { + return fromString(name, IdentityType.class); + } + + /** + * @return known IdentityType values + */ + public static Collection values() { + return values(IdentityType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/KeyVaultCredentialSettings.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/KeyVaultCredentialSettings.java new file mode 100644 index 0000000000000..b5263dbfcb52e --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/KeyVaultCredentialSettings.java @@ -0,0 +1,148 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Configure your SQL virtual machine to be able to connect to the Azure Key + * Vault service. + */ +public class KeyVaultCredentialSettings { + /** + * Enable or disable key vault credential setting. + */ + @JsonProperty(value = "enable") + private Boolean enable; + + /** + * Credential name. + */ + @JsonProperty(value = "credentialName") + private String credentialName; + + /** + * Azure Key Vault url. + */ + @JsonProperty(value = "azureKeyVaultUrl") + private String azureKeyVaultUrl; + + /** + * Service principal name to access key vault. + */ + @JsonProperty(value = "servicePrincipalName") + private String servicePrincipalName; + + /** + * Service principal name secret to access key vault. + */ + @JsonProperty(value = "servicePrincipalSecret") + private String servicePrincipalSecret; + + /** + * Get enable or disable key vault credential setting. + * + * @return the enable value + */ + public Boolean enable() { + return this.enable; + } + + /** + * Set enable or disable key vault credential setting. + * + * @param enable the enable value to set + * @return the KeyVaultCredentialSettings object itself. + */ + public KeyVaultCredentialSettings withEnable(Boolean enable) { + this.enable = enable; + return this; + } + + /** + * Get credential name. + * + * @return the credentialName value + */ + public String credentialName() { + return this.credentialName; + } + + /** + * Set credential name. + * + * @param credentialName the credentialName value to set + * @return the KeyVaultCredentialSettings object itself. + */ + public KeyVaultCredentialSettings withCredentialName(String credentialName) { + this.credentialName = credentialName; + return this; + } + + /** + * Get azure Key Vault url. + * + * @return the azureKeyVaultUrl value + */ + public String azureKeyVaultUrl() { + return this.azureKeyVaultUrl; + } + + /** + * Set azure Key Vault url. + * + * @param azureKeyVaultUrl the azureKeyVaultUrl value to set + * @return the KeyVaultCredentialSettings object itself. + */ + public KeyVaultCredentialSettings withAzureKeyVaultUrl(String azureKeyVaultUrl) { + this.azureKeyVaultUrl = azureKeyVaultUrl; + return this; + } + + /** + * Get service principal name to access key vault. + * + * @return the servicePrincipalName value + */ + public String servicePrincipalName() { + return this.servicePrincipalName; + } + + /** + * Set service principal name to access key vault. + * + * @param servicePrincipalName the servicePrincipalName value to set + * @return the KeyVaultCredentialSettings object itself. + */ + public KeyVaultCredentialSettings withServicePrincipalName(String servicePrincipalName) { + this.servicePrincipalName = servicePrincipalName; + return this; + } + + /** + * Get service principal name secret to access key vault. + * + * @return the servicePrincipalSecret value + */ + public String servicePrincipalSecret() { + return this.servicePrincipalSecret; + } + + /** + * Set service principal name secret to access key vault. + * + * @param servicePrincipalSecret the servicePrincipalSecret value to set + * @return the KeyVaultCredentialSettings object itself. + */ + public KeyVaultCredentialSettings withServicePrincipalSecret(String servicePrincipalSecret) { + this.servicePrincipalSecret = servicePrincipalSecret; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/LoadBalancerConfiguration.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/LoadBalancerConfiguration.java new file mode 100644 index 0000000000000..cf0aeb67f0639 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/LoadBalancerConfiguration.java @@ -0,0 +1,149 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A load balancer configuration for an availability group listener. + */ +public class LoadBalancerConfiguration { + /** + * Private IP address. + */ + @JsonProperty(value = "privateIpAddress") + private PrivateIPAddress privateIpAddress; + + /** + * Resource id of the public IP. + */ + @JsonProperty(value = "publicIpAddressResourceId") + private String publicIpAddressResourceId; + + /** + * Resource id of the load balancer. + */ + @JsonProperty(value = "loadBalancerResourceId") + private String loadBalancerResourceId; + + /** + * Probe port. + */ + @JsonProperty(value = "probePort") + private Integer probePort; + + /** + * List of the SQL virtual machine instance resource id's that are enrolled + * into the availability group listener. + */ + @JsonProperty(value = "sqlVirtualMachineInstances") + private List sqlVirtualMachineInstances; + + /** + * Get private IP address. + * + * @return the privateIpAddress value + */ + public PrivateIPAddress privateIpAddress() { + return this.privateIpAddress; + } + + /** + * Set private IP address. + * + * @param privateIpAddress the privateIpAddress value to set + * @return the LoadBalancerConfiguration object itself. + */ + public LoadBalancerConfiguration withPrivateIpAddress(PrivateIPAddress privateIpAddress) { + this.privateIpAddress = privateIpAddress; + return this; + } + + /** + * Get resource id of the public IP. + * + * @return the publicIpAddressResourceId value + */ + public String publicIpAddressResourceId() { + return this.publicIpAddressResourceId; + } + + /** + * Set resource id of the public IP. + * + * @param publicIpAddressResourceId the publicIpAddressResourceId value to set + * @return the LoadBalancerConfiguration object itself. + */ + public LoadBalancerConfiguration withPublicIpAddressResourceId(String publicIpAddressResourceId) { + this.publicIpAddressResourceId = publicIpAddressResourceId; + return this; + } + + /** + * Get resource id of the load balancer. + * + * @return the loadBalancerResourceId value + */ + public String loadBalancerResourceId() { + return this.loadBalancerResourceId; + } + + /** + * Set resource id of the load balancer. + * + * @param loadBalancerResourceId the loadBalancerResourceId value to set + * @return the LoadBalancerConfiguration object itself. + */ + public LoadBalancerConfiguration withLoadBalancerResourceId(String loadBalancerResourceId) { + this.loadBalancerResourceId = loadBalancerResourceId; + return this; + } + + /** + * Get probe port. + * + * @return the probePort value + */ + public Integer probePort() { + return this.probePort; + } + + /** + * Set probe port. + * + * @param probePort the probePort value to set + * @return the LoadBalancerConfiguration object itself. + */ + public LoadBalancerConfiguration withProbePort(Integer probePort) { + this.probePort = probePort; + return this; + } + + /** + * Get list of the SQL virtual machine instance resource id's that are enrolled into the availability group listener. + * + * @return the sqlVirtualMachineInstances value + */ + public List sqlVirtualMachineInstances() { + return this.sqlVirtualMachineInstances; + } + + /** + * Set list of the SQL virtual machine instance resource id's that are enrolled into the availability group listener. + * + * @param sqlVirtualMachineInstances the sqlVirtualMachineInstances value to set + * @return the LoadBalancerConfiguration object itself. + */ + public LoadBalancerConfiguration withSqlVirtualMachineInstances(List sqlVirtualMachineInstances) { + this.sqlVirtualMachineInstances = sqlVirtualMachineInstances; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/Operation.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/Operation.java new file mode 100644 index 0000000000000..e4fce18924da7 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/Operation.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.SqlVirtualMachineManager; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.OperationInner; +import java.util.Map; + +/** + * Type representing Operation. + */ +public interface Operation extends HasInner, HasManager { + /** + * @return the display value. + */ + OperationDisplay display(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the origin value. + */ + OperationOrigin origin(); + + /** + * @return the properties value. + */ + Map properties(); + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/OperationDisplay.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/OperationDisplay.java new file mode 100644 index 0000000000000..2b9ad6ddd2efd --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/OperationDisplay.java @@ -0,0 +1,78 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Display metadata associated with the operation. + */ +public class OperationDisplay { + /** + * The localized friendly form of the resource provider name. + */ + @JsonProperty(value = "provider", access = JsonProperty.Access.WRITE_ONLY) + private String provider; + + /** + * The localized friendly form of the resource type related to this + * action/operation. + */ + @JsonProperty(value = "resource", access = JsonProperty.Access.WRITE_ONLY) + private String resource; + + /** + * The localized friendly name for the operation. + */ + @JsonProperty(value = "operation", access = JsonProperty.Access.WRITE_ONLY) + private String operation; + + /** + * The localized friendly description for the operation. + */ + @JsonProperty(value = "description", access = JsonProperty.Access.WRITE_ONLY) + private String description; + + /** + * Get the localized friendly form of the resource provider name. + * + * @return the provider value + */ + public String provider() { + return this.provider; + } + + /** + * Get the localized friendly form of the resource type related to this action/operation. + * + * @return the resource value + */ + public String resource() { + return this.resource; + } + + /** + * Get the localized friendly name for the operation. + * + * @return the operation value + */ + public String operation() { + return this.operation; + } + + /** + * Get the localized friendly description for the operation. + * + * @return the description value + */ + public String description() { + return this.description; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/OperationOrigin.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/OperationOrigin.java new file mode 100644 index 0000000000000..daefb0e3e9e15 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/OperationOrigin.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for OperationOrigin. + */ +public final class OperationOrigin extends ExpandableStringEnum { + /** Static value user for OperationOrigin. */ + public static final OperationOrigin USER = fromString("user"); + + /** Static value system for OperationOrigin. */ + public static final OperationOrigin SYSTEM = fromString("system"); + + /** + * Creates or finds a OperationOrigin from its string representation. + * @param name a name to look for + * @return the corresponding OperationOrigin + */ + @JsonCreator + public static OperationOrigin fromString(String name) { + return fromString(name, OperationOrigin.class); + } + + /** + * @return known OperationOrigin values + */ + public static Collection values() { + return values(OperationOrigin.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/Operations.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/Operations.java new file mode 100644 index 0000000000000..a52610ee0cc67 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/Operations.java @@ -0,0 +1,27 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import rx.Observable; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.OperationsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Operations. + */ +public interface Operations extends HasInner { + /** + * Lists all of the available SQL Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/PrivateIPAddress.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/PrivateIPAddress.java new file mode 100644 index 0000000000000..28139b8869257 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/PrivateIPAddress.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A private IP address bound to the availability group listener. + */ +public class PrivateIPAddress { + /** + * Private IP address bound to the availability group listener. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * Subnet used to include private IP. + */ + @JsonProperty(value = "subnetResourceId") + private String subnetResourceId; + + /** + * Get private IP address bound to the availability group listener. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set private IP address bound to the availability group listener. + * + * @param ipAddress the ipAddress value to set + * @return the PrivateIPAddress object itself. + */ + public PrivateIPAddress withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get subnet used to include private IP. + * + * @return the subnetResourceId value + */ + public String subnetResourceId() { + return this.subnetResourceId; + } + + /** + * Set subnet used to include private IP. + * + * @param subnetResourceId the subnetResourceId value to set + * @return the PrivateIPAddress object itself. + */ + public PrivateIPAddress withSubnetResourceId(String subnetResourceId) { + this.subnetResourceId = subnetResourceId; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ResourceIdentity.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ResourceIdentity.java new file mode 100644 index 0000000000000..f36df36d76775 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ResourceIdentity.java @@ -0,0 +1,76 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.UUID; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Azure Active Directory identity configuration for a resource. + */ +public class ResourceIdentity { + /** + * The Azure Active Directory principal id. + */ + @JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY) + private UUID principalId; + + /** + * The identity type. Set this to 'SystemAssigned' in order to + * automatically create and assign an Azure Active Directory principal for + * the resource. Possible values include: 'SystemAssigned'. + */ + @JsonProperty(value = "type") + private IdentityType type; + + /** + * The Azure Active Directory tenant id. + */ + @JsonProperty(value = "tenantId", access = JsonProperty.Access.WRITE_ONLY) + private UUID tenantId; + + /** + * Get the Azure Active Directory principal id. + * + * @return the principalId value + */ + public UUID principalId() { + return this.principalId; + } + + /** + * Get the identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource. Possible values include: 'SystemAssigned'. + * + * @return the type value + */ + public IdentityType type() { + return this.type; + } + + /** + * Set the identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resource. Possible values include: 'SystemAssigned'. + * + * @param type the type value to set + * @return the ResourceIdentity object itself. + */ + public ResourceIdentity withType(IdentityType type) { + this.type = type; + return this; + } + + /** + * Get the Azure Active Directory tenant id. + * + * @return the tenantId value + */ + public UUID tenantId() { + return this.tenantId; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ScaleType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ScaleType.java new file mode 100644 index 0000000000000..5f6300f9e63d2 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ScaleType.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for ScaleType. + */ +public final class ScaleType extends ExpandableStringEnum { + /** Static value HA for ScaleType. */ + public static final ScaleType HA = fromString("HA"); + + /** + * Creates or finds a ScaleType from its string representation. + * @param name a name to look for + * @return the corresponding ScaleType + */ + @JsonCreator + public static ScaleType fromString(String name) { + return fromString(name, ScaleType.class); + } + + /** + * @return known ScaleType values + */ + public static Collection values() { + return values(ScaleType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ServerConfigurationsManagementSettings.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ServerConfigurationsManagementSettings.java new file mode 100644 index 0000000000000..8cde29e6616d7 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/ServerConfigurationsManagementSettings.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Set the connectivity, storage and workload settings. + */ +public class ServerConfigurationsManagementSettings { + /** + * SQL connectivity type settings. + */ + @JsonProperty(value = "sqlConnectivityUpdateSettings") + private SqlConnectivityUpdateSettings sqlConnectivityUpdateSettings; + + /** + * SQL workload type settings. + */ + @JsonProperty(value = "sqlWorkloadTypeUpdateSettings") + private SqlWorkloadTypeUpdateSettings sqlWorkloadTypeUpdateSettings; + + /** + * SQL storage update settings. + */ + @JsonProperty(value = "sqlStorageUpdateSettings") + private SqlStorageUpdateSettings sqlStorageUpdateSettings; + + /** + * Additional SQL feature settings. + */ + @JsonProperty(value = "additionalFeaturesServerConfigurations") + private AdditionalFeaturesServerConfigurations additionalFeaturesServerConfigurations; + + /** + * Get sQL connectivity type settings. + * + * @return the sqlConnectivityUpdateSettings value + */ + public SqlConnectivityUpdateSettings sqlConnectivityUpdateSettings() { + return this.sqlConnectivityUpdateSettings; + } + + /** + * Set sQL connectivity type settings. + * + * @param sqlConnectivityUpdateSettings the sqlConnectivityUpdateSettings value to set + * @return the ServerConfigurationsManagementSettings object itself. + */ + public ServerConfigurationsManagementSettings withSqlConnectivityUpdateSettings(SqlConnectivityUpdateSettings sqlConnectivityUpdateSettings) { + this.sqlConnectivityUpdateSettings = sqlConnectivityUpdateSettings; + return this; + } + + /** + * Get sQL workload type settings. + * + * @return the sqlWorkloadTypeUpdateSettings value + */ + public SqlWorkloadTypeUpdateSettings sqlWorkloadTypeUpdateSettings() { + return this.sqlWorkloadTypeUpdateSettings; + } + + /** + * Set sQL workload type settings. + * + * @param sqlWorkloadTypeUpdateSettings the sqlWorkloadTypeUpdateSettings value to set + * @return the ServerConfigurationsManagementSettings object itself. + */ + public ServerConfigurationsManagementSettings withSqlWorkloadTypeUpdateSettings(SqlWorkloadTypeUpdateSettings sqlWorkloadTypeUpdateSettings) { + this.sqlWorkloadTypeUpdateSettings = sqlWorkloadTypeUpdateSettings; + return this; + } + + /** + * Get sQL storage update settings. + * + * @return the sqlStorageUpdateSettings value + */ + public SqlStorageUpdateSettings sqlStorageUpdateSettings() { + return this.sqlStorageUpdateSettings; + } + + /** + * Set sQL storage update settings. + * + * @param sqlStorageUpdateSettings the sqlStorageUpdateSettings value to set + * @return the ServerConfigurationsManagementSettings object itself. + */ + public ServerConfigurationsManagementSettings withSqlStorageUpdateSettings(SqlStorageUpdateSettings sqlStorageUpdateSettings) { + this.sqlStorageUpdateSettings = sqlStorageUpdateSettings; + return this; + } + + /** + * Get additional SQL feature settings. + * + * @return the additionalFeaturesServerConfigurations value + */ + public AdditionalFeaturesServerConfigurations additionalFeaturesServerConfigurations() { + return this.additionalFeaturesServerConfigurations; + } + + /** + * Set additional SQL feature settings. + * + * @param additionalFeaturesServerConfigurations the additionalFeaturesServerConfigurations value to set + * @return the ServerConfigurationsManagementSettings object itself. + */ + public ServerConfigurationsManagementSettings withAdditionalFeaturesServerConfigurations(AdditionalFeaturesServerConfigurations additionalFeaturesServerConfigurations) { + this.additionalFeaturesServerConfigurations = additionalFeaturesServerConfigurations; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlConnectivityUpdateSettings.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlConnectivityUpdateSettings.java new file mode 100644 index 0000000000000..9b507da62998a --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlConnectivityUpdateSettings.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Set the access level and network port settings for SQL Server. + */ +public class SqlConnectivityUpdateSettings { + /** + * SQL Server connectivity option. Possible values include: 'LOCAL', + * 'PRIVATE', 'PUBLIC'. + */ + @JsonProperty(value = "connectivityType") + private ConnectivityType connectivityType; + + /** + * SQL Server port. + */ + @JsonProperty(value = "port") + private Integer port; + + /** + * SQL Server sysadmin login to create. + */ + @JsonProperty(value = "sqlAuthUpdateUserName") + private String sqlAuthUpdateUserName; + + /** + * SQL Server sysadmin login password. + */ + @JsonProperty(value = "sqlAuthUpdatePassword") + private String sqlAuthUpdatePassword; + + /** + * Get sQL Server connectivity option. Possible values include: 'LOCAL', 'PRIVATE', 'PUBLIC'. + * + * @return the connectivityType value + */ + public ConnectivityType connectivityType() { + return this.connectivityType; + } + + /** + * Set sQL Server connectivity option. Possible values include: 'LOCAL', 'PRIVATE', 'PUBLIC'. + * + * @param connectivityType the connectivityType value to set + * @return the SqlConnectivityUpdateSettings object itself. + */ + public SqlConnectivityUpdateSettings withConnectivityType(ConnectivityType connectivityType) { + this.connectivityType = connectivityType; + return this; + } + + /** + * Get sQL Server port. + * + * @return the port value + */ + public Integer port() { + return this.port; + } + + /** + * Set sQL Server port. + * + * @param port the port value to set + * @return the SqlConnectivityUpdateSettings object itself. + */ + public SqlConnectivityUpdateSettings withPort(Integer port) { + this.port = port; + return this; + } + + /** + * Get sQL Server sysadmin login to create. + * + * @return the sqlAuthUpdateUserName value + */ + public String sqlAuthUpdateUserName() { + return this.sqlAuthUpdateUserName; + } + + /** + * Set sQL Server sysadmin login to create. + * + * @param sqlAuthUpdateUserName the sqlAuthUpdateUserName value to set + * @return the SqlConnectivityUpdateSettings object itself. + */ + public SqlConnectivityUpdateSettings withSqlAuthUpdateUserName(String sqlAuthUpdateUserName) { + this.sqlAuthUpdateUserName = sqlAuthUpdateUserName; + return this; + } + + /** + * Get sQL Server sysadmin login password. + * + * @return the sqlAuthUpdatePassword value + */ + public String sqlAuthUpdatePassword() { + return this.sqlAuthUpdatePassword; + } + + /** + * Set sQL Server sysadmin login password. + * + * @param sqlAuthUpdatePassword the sqlAuthUpdatePassword value to set + * @return the SqlConnectivityUpdateSettings object itself. + */ + public SqlConnectivityUpdateSettings withSqlAuthUpdatePassword(String sqlAuthUpdatePassword) { + this.sqlAuthUpdatePassword = sqlAuthUpdatePassword; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlImageSku.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlImageSku.java new file mode 100644 index 0000000000000..0c42bddd3ba24 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlImageSku.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for SqlImageSku. + */ +public final class SqlImageSku extends ExpandableStringEnum { + /** Static value Developer for SqlImageSku. */ + public static final SqlImageSku DEVELOPER = fromString("Developer"); + + /** Static value Express for SqlImageSku. */ + public static final SqlImageSku EXPRESS = fromString("Express"); + + /** Static value Standard for SqlImageSku. */ + public static final SqlImageSku STANDARD = fromString("Standard"); + + /** Static value Enterprise for SqlImageSku. */ + public static final SqlImageSku ENTERPRISE = fromString("Enterprise"); + + /** Static value Web for SqlImageSku. */ + public static final SqlImageSku WEB = fromString("Web"); + + /** + * Creates or finds a SqlImageSku from its string representation. + * @param name a name to look for + * @return the corresponding SqlImageSku + */ + @JsonCreator + public static SqlImageSku fromString(String name) { + return fromString(name, SqlImageSku.class); + } + + /** + * @return known SqlImageSku values + */ + public static Collection values() { + return values(SqlImageSku.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlManagementMode.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlManagementMode.java new file mode 100644 index 0000000000000..2832caa2b0b85 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlManagementMode.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for SqlManagementMode. + */ +public final class SqlManagementMode extends ExpandableStringEnum { + /** Static value Full for SqlManagementMode. */ + public static final SqlManagementMode FULL = fromString("Full"); + + /** Static value LightWeight for SqlManagementMode. */ + public static final SqlManagementMode LIGHT_WEIGHT = fromString("LightWeight"); + + /** Static value NoAgent for SqlManagementMode. */ + public static final SqlManagementMode NO_AGENT = fromString("NoAgent"); + + /** + * Creates or finds a SqlManagementMode from its string representation. + * @param name a name to look for + * @return the corresponding SqlManagementMode + */ + @JsonCreator + public static SqlManagementMode fromString(String name) { + return fromString(name, SqlManagementMode.class); + } + + /** + * @return known SqlManagementMode values + */ + public static Collection values() { + return values(SqlManagementMode.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlServerLicenseType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlServerLicenseType.java new file mode 100644 index 0000000000000..6825e7a17c2d2 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlServerLicenseType.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for SqlServerLicenseType. + */ +public final class SqlServerLicenseType extends ExpandableStringEnum { + /** Static value PAYG for SqlServerLicenseType. */ + public static final SqlServerLicenseType PAYG = fromString("PAYG"); + + /** Static value AHUB for SqlServerLicenseType. */ + public static final SqlServerLicenseType AHUB = fromString("AHUB"); + + /** + * Creates or finds a SqlServerLicenseType from its string representation. + * @param name a name to look for + * @return the corresponding SqlServerLicenseType + */ + @JsonCreator + public static SqlServerLicenseType fromString(String name) { + return fromString(name, SqlServerLicenseType.class); + } + + /** + * @return known SqlServerLicenseType values + */ + public static Collection values() { + return values(SqlServerLicenseType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlStorageUpdateSettings.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlStorageUpdateSettings.java new file mode 100644 index 0000000000000..f6c9015d6e50d --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlStorageUpdateSettings.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Set disk storage settings for SQL Server. + */ +public class SqlStorageUpdateSettings { + /** + * Virtual machine disk count. + */ + @JsonProperty(value = "diskCount") + private Integer diskCount; + + /** + * Device id of the first disk to be updated. + */ + @JsonProperty(value = "startingDeviceId") + private Integer startingDeviceId; + + /** + * Disk configuration to apply to SQL Server. Possible values include: + * 'NEW', 'EXTEND', 'ADD'. + */ + @JsonProperty(value = "diskConfigurationType") + private DiskConfigurationType diskConfigurationType; + + /** + * Get virtual machine disk count. + * + * @return the diskCount value + */ + public Integer diskCount() { + return this.diskCount; + } + + /** + * Set virtual machine disk count. + * + * @param diskCount the diskCount value to set + * @return the SqlStorageUpdateSettings object itself. + */ + public SqlStorageUpdateSettings withDiskCount(Integer diskCount) { + this.diskCount = diskCount; + return this; + } + + /** + * Get device id of the first disk to be updated. + * + * @return the startingDeviceId value + */ + public Integer startingDeviceId() { + return this.startingDeviceId; + } + + /** + * Set device id of the first disk to be updated. + * + * @param startingDeviceId the startingDeviceId value to set + * @return the SqlStorageUpdateSettings object itself. + */ + public SqlStorageUpdateSettings withStartingDeviceId(Integer startingDeviceId) { + this.startingDeviceId = startingDeviceId; + return this; + } + + /** + * Get disk configuration to apply to SQL Server. Possible values include: 'NEW', 'EXTEND', 'ADD'. + * + * @return the diskConfigurationType value + */ + public DiskConfigurationType diskConfigurationType() { + return this.diskConfigurationType; + } + + /** + * Set disk configuration to apply to SQL Server. Possible values include: 'NEW', 'EXTEND', 'ADD'. + * + * @param diskConfigurationType the diskConfigurationType value to set + * @return the SqlStorageUpdateSettings object itself. + */ + public SqlStorageUpdateSettings withDiskConfigurationType(DiskConfigurationType diskConfigurationType) { + this.diskConfigurationType = diskConfigurationType; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachine.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachine.java new file mode 100644 index 0000000000000..6ab9c2f4896c0 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachine.java @@ -0,0 +1,421 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.Resource; +import com.microsoft.azure.arm.resources.models.GroupableResourceCore; +import com.microsoft.azure.arm.resources.models.HasResourceGroup; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.SqlVirtualMachineManager; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.SqlVirtualMachineInner; + +/** + * Type representing SqlVirtualMachine. + */ +public interface SqlVirtualMachine extends HasInner, Resource, GroupableResourceCore, HasResourceGroup, Refreshable, Updatable, HasManager { + /** + * @return the autoBackupSettings value. + */ + AutoBackupSettings autoBackupSettings(); + + /** + * @return the autoPatchingSettings value. + */ + AutoPatchingSettings autoPatchingSettings(); + + /** + * @return the identity value. + */ + ResourceIdentity identity(); + + /** + * @return the keyVaultCredentialSettings value. + */ + KeyVaultCredentialSettings keyVaultCredentialSettings(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * @return the serverConfigurationsManagementSettings value. + */ + ServerConfigurationsManagementSettings serverConfigurationsManagementSettings(); + + /** + * @return the sqlImageOffer value. + */ + String sqlImageOffer(); + + /** + * @return the sqlImageSku value. + */ + SqlImageSku sqlImageSku(); + + /** + * @return the sqlManagement value. + */ + SqlManagementMode sqlManagement(); + + /** + * @return the sqlServerLicenseType value. + */ + SqlServerLicenseType sqlServerLicenseType(); + + /** + * @return the sqlVirtualMachineGroupResourceId value. + */ + String sqlVirtualMachineGroupResourceId(); + + /** + * @return the virtualMachineResourceId value. + */ + String virtualMachineResourceId(); + + /** + * @return the wsfcDomainCredentials value. + */ + WsfcDomainCredentials wsfcDomainCredentials(); + + /** + * The entirety of the SqlVirtualMachine definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate { + } + + /** + * Grouping of SqlVirtualMachine definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a SqlVirtualMachine definition. + */ + interface Blank extends GroupableResourceCore.DefinitionWithRegion { + } + + /** + * The stage of the SqlVirtualMachine definition allowing to specify the resource group. + */ + interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup { + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify AutoBackupSettings. + */ + interface WithAutoBackupSettings { + /** + * Specifies autoBackupSettings. + * @param autoBackupSettings Auto backup settings for SQL Server + * @return the next definition stage + */ + WithCreate withAutoBackupSettings(AutoBackupSettings autoBackupSettings); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify AutoPatchingSettings. + */ + interface WithAutoPatchingSettings { + /** + * Specifies autoPatchingSettings. + * @param autoPatchingSettings Auto patching settings for applying critical security updates to SQL virtual machine + * @return the next definition stage + */ + WithCreate withAutoPatchingSettings(AutoPatchingSettings autoPatchingSettings); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify Identity. + */ + interface WithIdentity { + /** + * Specifies identity. + * @param identity Azure Active Directory identity of the server + * @return the next definition stage + */ + WithCreate withIdentity(ResourceIdentity identity); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify KeyVaultCredentialSettings. + */ + interface WithKeyVaultCredentialSettings { + /** + * Specifies keyVaultCredentialSettings. + * @param keyVaultCredentialSettings Key vault credential settings + * @return the next definition stage + */ + WithCreate withKeyVaultCredentialSettings(KeyVaultCredentialSettings keyVaultCredentialSettings); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify ServerConfigurationsManagementSettings. + */ + interface WithServerConfigurationsManagementSettings { + /** + * Specifies serverConfigurationsManagementSettings. + * @param serverConfigurationsManagementSettings SQL Server configuration management settings + * @return the next definition stage + */ + WithCreate withServerConfigurationsManagementSettings(ServerConfigurationsManagementSettings serverConfigurationsManagementSettings); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify SqlImageOffer. + */ + interface WithSqlImageOffer { + /** + * Specifies sqlImageOffer. + * @param sqlImageOffer SQL image offer. Examples include SQL2016-WS2016, SQL2017-WS2016 + * @return the next definition stage + */ + WithCreate withSqlImageOffer(String sqlImageOffer); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify SqlImageSku. + */ + interface WithSqlImageSku { + /** + * Specifies sqlImageSku. + * @param sqlImageSku SQL Server edition type. Possible values include: 'Developer', 'Express', 'Standard', 'Enterprise', 'Web' + * @return the next definition stage + */ + WithCreate withSqlImageSku(SqlImageSku sqlImageSku); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify SqlManagement. + */ + interface WithSqlManagement { + /** + * Specifies sqlManagement. + * @param sqlManagement SQL Server Management type. Possible values include: 'Full', 'LightWeight', 'NoAgent' + * @return the next definition stage + */ + WithCreate withSqlManagement(SqlManagementMode sqlManagement); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify SqlServerLicenseType. + */ + interface WithSqlServerLicenseType { + /** + * Specifies sqlServerLicenseType. + * @param sqlServerLicenseType SQL Server license type. Possible values include: 'PAYG', 'AHUB' + * @return the next definition stage + */ + WithCreate withSqlServerLicenseType(SqlServerLicenseType sqlServerLicenseType); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify SqlVirtualMachineGroupResourceId. + */ + interface WithSqlVirtualMachineGroupResourceId { + /** + * Specifies sqlVirtualMachineGroupResourceId. + * @param sqlVirtualMachineGroupResourceId ARM resource id of the SQL virtual machine group this SQL virtual machine is or will be part of + * @return the next definition stage + */ + WithCreate withSqlVirtualMachineGroupResourceId(String sqlVirtualMachineGroupResourceId); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify VirtualMachineResourceId. + */ + interface WithVirtualMachineResourceId { + /** + * Specifies virtualMachineResourceId. + * @param virtualMachineResourceId ARM Resource id of underlying virtual machine created from SQL marketplace image + * @return the next definition stage + */ + WithCreate withVirtualMachineResourceId(String virtualMachineResourceId); + } + + /** + * The stage of the sqlvirtualmachine definition allowing to specify WsfcDomainCredentials. + */ + interface WithWsfcDomainCredentials { + /** + * Specifies wsfcDomainCredentials. + * @param wsfcDomainCredentials Domain credentials for setting up Windows Server Failover Cluster for SQL availability group + * @return the next definition stage + */ + WithCreate withWsfcDomainCredentials(WsfcDomainCredentials wsfcDomainCredentials); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, Resource.DefinitionWithTags, DefinitionStages.WithAutoBackupSettings, DefinitionStages.WithAutoPatchingSettings, DefinitionStages.WithIdentity, DefinitionStages.WithKeyVaultCredentialSettings, DefinitionStages.WithServerConfigurationsManagementSettings, DefinitionStages.WithSqlImageOffer, DefinitionStages.WithSqlImageSku, DefinitionStages.WithSqlManagement, DefinitionStages.WithSqlServerLicenseType, DefinitionStages.WithSqlVirtualMachineGroupResourceId, DefinitionStages.WithVirtualMachineResourceId, DefinitionStages.WithWsfcDomainCredentials { + } + } + /** + * The template for a SqlVirtualMachine update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithAutoBackupSettings, UpdateStages.WithAutoPatchingSettings, UpdateStages.WithIdentity, UpdateStages.WithKeyVaultCredentialSettings, UpdateStages.WithServerConfigurationsManagementSettings, UpdateStages.WithSqlImageOffer, UpdateStages.WithSqlImageSku, UpdateStages.WithSqlManagement, UpdateStages.WithSqlServerLicenseType, UpdateStages.WithSqlVirtualMachineGroupResourceId, UpdateStages.WithVirtualMachineResourceId, UpdateStages.WithWsfcDomainCredentials { + } + + /** + * Grouping of SqlVirtualMachine update stages. + */ + interface UpdateStages { + /** + * The stage of the sqlvirtualmachine update allowing to specify AutoBackupSettings. + */ + interface WithAutoBackupSettings { + /** + * Specifies autoBackupSettings. + * @param autoBackupSettings Auto backup settings for SQL Server + * @return the next update stage + */ + Update withAutoBackupSettings(AutoBackupSettings autoBackupSettings); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify AutoPatchingSettings. + */ + interface WithAutoPatchingSettings { + /** + * Specifies autoPatchingSettings. + * @param autoPatchingSettings Auto patching settings for applying critical security updates to SQL virtual machine + * @return the next update stage + */ + Update withAutoPatchingSettings(AutoPatchingSettings autoPatchingSettings); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify Identity. + */ + interface WithIdentity { + /** + * Specifies identity. + * @param identity Azure Active Directory identity of the server + * @return the next update stage + */ + Update withIdentity(ResourceIdentity identity); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify KeyVaultCredentialSettings. + */ + interface WithKeyVaultCredentialSettings { + /** + * Specifies keyVaultCredentialSettings. + * @param keyVaultCredentialSettings Key vault credential settings + * @return the next update stage + */ + Update withKeyVaultCredentialSettings(KeyVaultCredentialSettings keyVaultCredentialSettings); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify ServerConfigurationsManagementSettings. + */ + interface WithServerConfigurationsManagementSettings { + /** + * Specifies serverConfigurationsManagementSettings. + * @param serverConfigurationsManagementSettings SQL Server configuration management settings + * @return the next update stage + */ + Update withServerConfigurationsManagementSettings(ServerConfigurationsManagementSettings serverConfigurationsManagementSettings); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify SqlImageOffer. + */ + interface WithSqlImageOffer { + /** + * Specifies sqlImageOffer. + * @param sqlImageOffer SQL image offer. Examples include SQL2016-WS2016, SQL2017-WS2016 + * @return the next update stage + */ + Update withSqlImageOffer(String sqlImageOffer); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify SqlImageSku. + */ + interface WithSqlImageSku { + /** + * Specifies sqlImageSku. + * @param sqlImageSku SQL Server edition type. Possible values include: 'Developer', 'Express', 'Standard', 'Enterprise', 'Web' + * @return the next update stage + */ + Update withSqlImageSku(SqlImageSku sqlImageSku); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify SqlManagement. + */ + interface WithSqlManagement { + /** + * Specifies sqlManagement. + * @param sqlManagement SQL Server Management type. Possible values include: 'Full', 'LightWeight', 'NoAgent' + * @return the next update stage + */ + Update withSqlManagement(SqlManagementMode sqlManagement); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify SqlServerLicenseType. + */ + interface WithSqlServerLicenseType { + /** + * Specifies sqlServerLicenseType. + * @param sqlServerLicenseType SQL Server license type. Possible values include: 'PAYG', 'AHUB' + * @return the next update stage + */ + Update withSqlServerLicenseType(SqlServerLicenseType sqlServerLicenseType); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify SqlVirtualMachineGroupResourceId. + */ + interface WithSqlVirtualMachineGroupResourceId { + /** + * Specifies sqlVirtualMachineGroupResourceId. + * @param sqlVirtualMachineGroupResourceId ARM resource id of the SQL virtual machine group this SQL virtual machine is or will be part of + * @return the next update stage + */ + Update withSqlVirtualMachineGroupResourceId(String sqlVirtualMachineGroupResourceId); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify VirtualMachineResourceId. + */ + interface WithVirtualMachineResourceId { + /** + * Specifies virtualMachineResourceId. + * @param virtualMachineResourceId ARM Resource id of underlying virtual machine created from SQL marketplace image + * @return the next update stage + */ + Update withVirtualMachineResourceId(String virtualMachineResourceId); + } + + /** + * The stage of the sqlvirtualmachine update allowing to specify WsfcDomainCredentials. + */ + interface WithWsfcDomainCredentials { + /** + * Specifies wsfcDomainCredentials. + * @param wsfcDomainCredentials Domain credentials for setting up Windows Server Failover Cluster for SQL availability group + * @return the next update stage + */ + Update withWsfcDomainCredentials(WsfcDomainCredentials wsfcDomainCredentials); + } + + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroup.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroup.java new file mode 100644 index 0000000000000..e8697e906bc56 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroup.java @@ -0,0 +1,175 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.Resource; +import com.microsoft.azure.arm.resources.models.GroupableResourceCore; +import com.microsoft.azure.arm.resources.models.HasResourceGroup; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.SqlVirtualMachineManager; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.SqlVirtualMachineGroupInner; + +/** + * Type representing SqlVirtualMachineGroup. + */ +public interface SqlVirtualMachineGroup extends HasInner, Resource, GroupableResourceCore, HasResourceGroup, Refreshable, Updatable, HasManager { + /** + * @return the clusterConfiguration value. + */ + ClusterConfiguration clusterConfiguration(); + + /** + * @return the clusterManagerType value. + */ + ClusterManagerType clusterManagerType(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * @return the scaleType value. + */ + ScaleType scaleType(); + + /** + * @return the sqlImageOffer value. + */ + String sqlImageOffer(); + + /** + * @return the sqlImageSku value. + */ + SqlVmGroupImageSku sqlImageSku(); + + /** + * @return the wsfcDomainProfile value. + */ + WsfcDomainProfile wsfcDomainProfile(); + + /** + * The entirety of the SqlVirtualMachineGroup definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate { + } + + /** + * Grouping of SqlVirtualMachineGroup definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a SqlVirtualMachineGroup definition. + */ + interface Blank extends GroupableResourceCore.DefinitionWithRegion { + } + + /** + * The stage of the SqlVirtualMachineGroup definition allowing to specify the resource group. + */ + interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup { + } + + /** + * The stage of the sqlvirtualmachinegroup definition allowing to specify SqlImageOffer. + */ + interface WithSqlImageOffer { + /** + * Specifies sqlImageOffer. + * @param sqlImageOffer SQL image offer. Examples may include SQL2016-WS2016, SQL2017-WS2016 + * @return the next definition stage + */ + WithCreate withSqlImageOffer(String sqlImageOffer); + } + + /** + * The stage of the sqlvirtualmachinegroup definition allowing to specify SqlImageSku. + */ + interface WithSqlImageSku { + /** + * Specifies sqlImageSku. + * @param sqlImageSku SQL image sku. Possible values include: 'Developer', 'Enterprise' + * @return the next definition stage + */ + WithCreate withSqlImageSku(SqlVmGroupImageSku sqlImageSku); + } + + /** + * The stage of the sqlvirtualmachinegroup definition allowing to specify WsfcDomainProfile. + */ + interface WithWsfcDomainProfile { + /** + * Specifies wsfcDomainProfile. + * @param wsfcDomainProfile Cluster Active Directory domain profile + * @return the next definition stage + */ + WithCreate withWsfcDomainProfile(WsfcDomainProfile wsfcDomainProfile); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, Resource.DefinitionWithTags, DefinitionStages.WithSqlImageOffer, DefinitionStages.WithSqlImageSku, DefinitionStages.WithWsfcDomainProfile { + } + } + /** + * The template for a SqlVirtualMachineGroup update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithSqlImageOffer, UpdateStages.WithSqlImageSku, UpdateStages.WithWsfcDomainProfile { + } + + /** + * Grouping of SqlVirtualMachineGroup update stages. + */ + interface UpdateStages { + /** + * The stage of the sqlvirtualmachinegroup update allowing to specify SqlImageOffer. + */ + interface WithSqlImageOffer { + /** + * Specifies sqlImageOffer. + * @param sqlImageOffer SQL image offer. Examples may include SQL2016-WS2016, SQL2017-WS2016 + * @return the next update stage + */ + Update withSqlImageOffer(String sqlImageOffer); + } + + /** + * The stage of the sqlvirtualmachinegroup update allowing to specify SqlImageSku. + */ + interface WithSqlImageSku { + /** + * Specifies sqlImageSku. + * @param sqlImageSku SQL image sku. Possible values include: 'Developer', 'Enterprise' + * @return the next update stage + */ + Update withSqlImageSku(SqlVmGroupImageSku sqlImageSku); + } + + /** + * The stage of the sqlvirtualmachinegroup update allowing to specify WsfcDomainProfile. + */ + interface WithWsfcDomainProfile { + /** + * Specifies wsfcDomainProfile. + * @param wsfcDomainProfile Cluster Active Directory domain profile + * @return the next update stage + */ + Update withWsfcDomainProfile(WsfcDomainProfile wsfcDomainProfile); + } + + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroupUpdate.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroupUpdate.java new file mode 100644 index 0000000000000..edfee48280a1d --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroupUpdate.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * An update to a SQL virtual machine group. + */ +public class SqlVirtualMachineGroupUpdate { + /** + * Resource tags. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get resource tags. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set resource tags. + * + * @param tags the tags value to set + * @return the SqlVirtualMachineGroupUpdate object itself. + */ + public SqlVirtualMachineGroupUpdate withTags(Map tags) { + this.tags = tags; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroups.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroups.java new file mode 100644 index 0000000000000..b92d0cfc035a6 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineGroups.java @@ -0,0 +1,25 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import com.microsoft.azure.arm.resources.collection.SupportsDeletingByResourceGroup; +import com.microsoft.azure.arm.resources.collection.SupportsBatchDeletion; +import com.microsoft.azure.arm.resources.collection.SupportsGettingByResourceGroup; +import rx.Observable; +import com.microsoft.azure.arm.resources.collection.SupportsListingByResourceGroup; +import com.microsoft.azure.arm.collection.SupportsListing; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.SqlVirtualMachineGroupsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing SqlVirtualMachineGroups. + */ +public interface SqlVirtualMachineGroups extends SupportsCreating, SupportsDeletingByResourceGroup, SupportsBatchDeletion, SupportsGettingByResourceGroup, SupportsListingByResourceGroup, SupportsListing, HasInner { +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineUpdate.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineUpdate.java new file mode 100644 index 0000000000000..30a83cd8013ed --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachineUpdate.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * An update to a SQL virtual machine. + */ +public class SqlVirtualMachineUpdate { + /** + * Resource tags. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get resource tags. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set resource tags. + * + * @param tags the tags value to set + * @return the SqlVirtualMachineUpdate object itself. + */ + public SqlVirtualMachineUpdate withTags(Map tags) { + this.tags = tags; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachines.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachines.java new file mode 100644 index 0000000000000..359f32a3574a4 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVirtualMachines.java @@ -0,0 +1,25 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import com.microsoft.azure.arm.resources.collection.SupportsDeletingByResourceGroup; +import com.microsoft.azure.arm.resources.collection.SupportsBatchDeletion; +import com.microsoft.azure.arm.resources.collection.SupportsGettingByResourceGroup; +import rx.Observable; +import com.microsoft.azure.arm.resources.collection.SupportsListingByResourceGroup; +import com.microsoft.azure.arm.collection.SupportsListing; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation.SqlVirtualMachinesInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing SqlVirtualMachines. + */ +public interface SqlVirtualMachines extends SupportsCreating, SupportsDeletingByResourceGroup, SupportsBatchDeletion, SupportsGettingByResourceGroup, SupportsListingByResourceGroup, SupportsListing, HasInner { +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVmGroupImageSku.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVmGroupImageSku.java new file mode 100644 index 0000000000000..c17a48c02975d --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlVmGroupImageSku.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for SqlVmGroupImageSku. + */ +public final class SqlVmGroupImageSku extends ExpandableStringEnum { + /** Static value Developer for SqlVmGroupImageSku. */ + public static final SqlVmGroupImageSku DEVELOPER = fromString("Developer"); + + /** Static value Enterprise for SqlVmGroupImageSku. */ + public static final SqlVmGroupImageSku ENTERPRISE = fromString("Enterprise"); + + /** + * Creates or finds a SqlVmGroupImageSku from its string representation. + * @param name a name to look for + * @return the corresponding SqlVmGroupImageSku + */ + @JsonCreator + public static SqlVmGroupImageSku fromString(String name) { + return fromString(name, SqlVmGroupImageSku.class); + } + + /** + * @return known SqlVmGroupImageSku values + */ + public static Collection values() { + return values(SqlVmGroupImageSku.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlWorkloadType.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlWorkloadType.java new file mode 100644 index 0000000000000..398f969f661ee --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlWorkloadType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for SqlWorkloadType. + */ +public final class SqlWorkloadType extends ExpandableStringEnum { + /** Static value GENERAL for SqlWorkloadType. */ + public static final SqlWorkloadType GENERAL = fromString("GENERAL"); + + /** Static value OLTP for SqlWorkloadType. */ + public static final SqlWorkloadType OLTP = fromString("OLTP"); + + /** Static value DW for SqlWorkloadType. */ + public static final SqlWorkloadType DW = fromString("DW"); + + /** + * Creates or finds a SqlWorkloadType from its string representation. + * @param name a name to look for + * @return the corresponding SqlWorkloadType + */ + @JsonCreator + public static SqlWorkloadType fromString(String name) { + return fromString(name, SqlWorkloadType.class); + } + + /** + * @return known SqlWorkloadType values + */ + public static Collection values() { + return values(SqlWorkloadType.class); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlWorkloadTypeUpdateSettings.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlWorkloadTypeUpdateSettings.java new file mode 100644 index 0000000000000..0d276338a161a --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/SqlWorkloadTypeUpdateSettings.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Set workload type to optimize storage for SQL Server. + */ +public class SqlWorkloadTypeUpdateSettings { + /** + * SQL Server workload type. Possible values include: 'GENERAL', 'OLTP', + * 'DW'. + */ + @JsonProperty(value = "sqlWorkloadType") + private SqlWorkloadType sqlWorkloadType; + + /** + * Get sQL Server workload type. Possible values include: 'GENERAL', 'OLTP', 'DW'. + * + * @return the sqlWorkloadType value + */ + public SqlWorkloadType sqlWorkloadType() { + return this.sqlWorkloadType; + } + + /** + * Set sQL Server workload type. Possible values include: 'GENERAL', 'OLTP', 'DW'. + * + * @param sqlWorkloadType the sqlWorkloadType value to set + * @return the SqlWorkloadTypeUpdateSettings object itself. + */ + public SqlWorkloadTypeUpdateSettings withSqlWorkloadType(SqlWorkloadType sqlWorkloadType) { + this.sqlWorkloadType = sqlWorkloadType; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/WsfcDomainCredentials.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/WsfcDomainCredentials.java new file mode 100644 index 0000000000000..09e86863fc77c --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/WsfcDomainCredentials.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Domain credentials for setting up Windows Server Failover Cluster for SQL + * availability group. + */ +public class WsfcDomainCredentials { + /** + * Cluster bootstrap account password. + */ + @JsonProperty(value = "clusterBootstrapAccountPassword") + private String clusterBootstrapAccountPassword; + + /** + * Cluster operator account password. + */ + @JsonProperty(value = "clusterOperatorAccountPassword") + private String clusterOperatorAccountPassword; + + /** + * SQL service account password. + */ + @JsonProperty(value = "sqlServiceAccountPassword") + private String sqlServiceAccountPassword; + + /** + * Get cluster bootstrap account password. + * + * @return the clusterBootstrapAccountPassword value + */ + public String clusterBootstrapAccountPassword() { + return this.clusterBootstrapAccountPassword; + } + + /** + * Set cluster bootstrap account password. + * + * @param clusterBootstrapAccountPassword the clusterBootstrapAccountPassword value to set + * @return the WsfcDomainCredentials object itself. + */ + public WsfcDomainCredentials withClusterBootstrapAccountPassword(String clusterBootstrapAccountPassword) { + this.clusterBootstrapAccountPassword = clusterBootstrapAccountPassword; + return this; + } + + /** + * Get cluster operator account password. + * + * @return the clusterOperatorAccountPassword value + */ + public String clusterOperatorAccountPassword() { + return this.clusterOperatorAccountPassword; + } + + /** + * Set cluster operator account password. + * + * @param clusterOperatorAccountPassword the clusterOperatorAccountPassword value to set + * @return the WsfcDomainCredentials object itself. + */ + public WsfcDomainCredentials withClusterOperatorAccountPassword(String clusterOperatorAccountPassword) { + this.clusterOperatorAccountPassword = clusterOperatorAccountPassword; + return this; + } + + /** + * Get sQL service account password. + * + * @return the sqlServiceAccountPassword value + */ + public String sqlServiceAccountPassword() { + return this.sqlServiceAccountPassword; + } + + /** + * Set sQL service account password. + * + * @param sqlServiceAccountPassword the sqlServiceAccountPassword value to set + * @return the WsfcDomainCredentials object itself. + */ + public WsfcDomainCredentials withSqlServiceAccountPassword(String sqlServiceAccountPassword) { + this.sqlServiceAccountPassword = sqlServiceAccountPassword; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/WsfcDomainProfile.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/WsfcDomainProfile.java new file mode 100644 index 0000000000000..a5a5adf5cda15 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/WsfcDomainProfile.java @@ -0,0 +1,229 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Active Directory account details to operate Windows Server Failover Cluster. + */ +public class WsfcDomainProfile { + /** + * Fully qualified name of the domain. + */ + @JsonProperty(value = "domainFqdn") + private String domainFqdn; + + /** + * Organizational Unit path in which the nodes and cluster will be present. + */ + @JsonProperty(value = "ouPath") + private String ouPath; + + /** + * Account name used for creating cluster (at minimum needs permissions to + * 'Create Computer Objects' in domain). + */ + @JsonProperty(value = "clusterBootstrapAccount") + private String clusterBootstrapAccount; + + /** + * Account name used for operating cluster i.e. will be part of + * administrators group on all the participating virtual machines in the + * cluster. + */ + @JsonProperty(value = "clusterOperatorAccount") + private String clusterOperatorAccount; + + /** + * Account name under which SQL service will run on all participating SQL + * virtual machines in the cluster. + */ + @JsonProperty(value = "sqlServiceAccount") + private String sqlServiceAccount; + + /** + * Optional path for fileshare witness. + */ + @JsonProperty(value = "fileShareWitnessPath") + private String fileShareWitnessPath; + + /** + * Fully qualified ARM resource id of the witness storage account. + */ + @JsonProperty(value = "storageAccountUrl") + private String storageAccountUrl; + + /** + * Primary key of the witness storage account. + */ + @JsonProperty(value = "storageAccountPrimaryKey") + private String storageAccountPrimaryKey; + + /** + * Get fully qualified name of the domain. + * + * @return the domainFqdn value + */ + public String domainFqdn() { + return this.domainFqdn; + } + + /** + * Set fully qualified name of the domain. + * + * @param domainFqdn the domainFqdn value to set + * @return the WsfcDomainProfile object itself. + */ + public WsfcDomainProfile withDomainFqdn(String domainFqdn) { + this.domainFqdn = domainFqdn; + return this; + } + + /** + * Get organizational Unit path in which the nodes and cluster will be present. + * + * @return the ouPath value + */ + public String ouPath() { + return this.ouPath; + } + + /** + * Set organizational Unit path in which the nodes and cluster will be present. + * + * @param ouPath the ouPath value to set + * @return the WsfcDomainProfile object itself. + */ + public WsfcDomainProfile withOuPath(String ouPath) { + this.ouPath = ouPath; + return this; + } + + /** + * Get account name used for creating cluster (at minimum needs permissions to 'Create Computer Objects' in domain). + * + * @return the clusterBootstrapAccount value + */ + public String clusterBootstrapAccount() { + return this.clusterBootstrapAccount; + } + + /** + * Set account name used for creating cluster (at minimum needs permissions to 'Create Computer Objects' in domain). + * + * @param clusterBootstrapAccount the clusterBootstrapAccount value to set + * @return the WsfcDomainProfile object itself. + */ + public WsfcDomainProfile withClusterBootstrapAccount(String clusterBootstrapAccount) { + this.clusterBootstrapAccount = clusterBootstrapAccount; + return this; + } + + /** + * Get account name used for operating cluster i.e. will be part of administrators group on all the participating virtual machines in the cluster. + * + * @return the clusterOperatorAccount value + */ + public String clusterOperatorAccount() { + return this.clusterOperatorAccount; + } + + /** + * Set account name used for operating cluster i.e. will be part of administrators group on all the participating virtual machines in the cluster. + * + * @param clusterOperatorAccount the clusterOperatorAccount value to set + * @return the WsfcDomainProfile object itself. + */ + public WsfcDomainProfile withClusterOperatorAccount(String clusterOperatorAccount) { + this.clusterOperatorAccount = clusterOperatorAccount; + return this; + } + + /** + * Get account name under which SQL service will run on all participating SQL virtual machines in the cluster. + * + * @return the sqlServiceAccount value + */ + public String sqlServiceAccount() { + return this.sqlServiceAccount; + } + + /** + * Set account name under which SQL service will run on all participating SQL virtual machines in the cluster. + * + * @param sqlServiceAccount the sqlServiceAccount value to set + * @return the WsfcDomainProfile object itself. + */ + public WsfcDomainProfile withSqlServiceAccount(String sqlServiceAccount) { + this.sqlServiceAccount = sqlServiceAccount; + return this; + } + + /** + * Get optional path for fileshare witness. + * + * @return the fileShareWitnessPath value + */ + public String fileShareWitnessPath() { + return this.fileShareWitnessPath; + } + + /** + * Set optional path for fileshare witness. + * + * @param fileShareWitnessPath the fileShareWitnessPath value to set + * @return the WsfcDomainProfile object itself. + */ + public WsfcDomainProfile withFileShareWitnessPath(String fileShareWitnessPath) { + this.fileShareWitnessPath = fileShareWitnessPath; + return this; + } + + /** + * Get fully qualified ARM resource id of the witness storage account. + * + * @return the storageAccountUrl value + */ + public String storageAccountUrl() { + return this.storageAccountUrl; + } + + /** + * Set fully qualified ARM resource id of the witness storage account. + * + * @param storageAccountUrl the storageAccountUrl value to set + * @return the WsfcDomainProfile object itself. + */ + public WsfcDomainProfile withStorageAccountUrl(String storageAccountUrl) { + this.storageAccountUrl = storageAccountUrl; + return this; + } + + /** + * Get primary key of the witness storage account. + * + * @return the storageAccountPrimaryKey value + */ + public String storageAccountPrimaryKey() { + return this.storageAccountPrimaryKey; + } + + /** + * Set primary key of the witness storage account. + * + * @param storageAccountPrimaryKey the storageAccountPrimaryKey value to set + * @return the WsfcDomainProfile object itself. + */ + public WsfcDomainProfile withStorageAccountPrimaryKey(String storageAccountPrimaryKey) { + this.storageAccountPrimaryKey = storageAccountPrimaryKey; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenerImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenerImpl.java new file mode 100644 index 0000000000000..82c1128a13be3 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenerImpl.java @@ -0,0 +1,145 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListener; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import java.util.List; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.LoadBalancerConfiguration; + +class AvailabilityGroupListenerImpl extends CreatableUpdatableImpl implements AvailabilityGroupListener, AvailabilityGroupListener.Definition, AvailabilityGroupListener.Update { + private final SqlVirtualMachineManager manager; + private String resourceGroupName; + private String sqlVirtualMachineGroupName; + private String availabilityGroupListenerName; + + AvailabilityGroupListenerImpl(String name, SqlVirtualMachineManager manager) { + super(name, new AvailabilityGroupListenerInner()); + this.manager = manager; + // Set resource name + this.availabilityGroupListenerName = name; + // + } + + AvailabilityGroupListenerImpl(AvailabilityGroupListenerInner inner, SqlVirtualMachineManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.availabilityGroupListenerName = inner.name(); + // set resource ancestor and positional variables + this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); + this.sqlVirtualMachineGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "sqlVirtualMachineGroups"); + this.availabilityGroupListenerName = IdParsingUtils.getValueFromIdByName(inner.id(), "availabilityGroupListeners"); + // + } + + @Override + public SqlVirtualMachineManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + AvailabilityGroupListenersInner client = this.manager().inner().availabilityGroupListeners(); + return client.createOrUpdateAsync(this.resourceGroupName, this.sqlVirtualMachineGroupName, this.availabilityGroupListenerName, this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + AvailabilityGroupListenersInner client = this.manager().inner().availabilityGroupListeners(); + return client.createOrUpdateAsync(this.resourceGroupName, this.sqlVirtualMachineGroupName, this.availabilityGroupListenerName, this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + AvailabilityGroupListenersInner client = this.manager().inner().availabilityGroupListeners(); + return client.getAsync(this.resourceGroupName, this.sqlVirtualMachineGroupName, this.availabilityGroupListenerName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + + @Override + public String availabilityGroupName() { + return this.inner().availabilityGroupName(); + } + + @Override + public Boolean createDefaultAvailabilityGroupIfNotExist() { + return this.inner().createDefaultAvailabilityGroupIfNotExist(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public List loadBalancerConfigurations() { + return this.inner().loadBalancerConfigurations(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public Integer port() { + return this.inner().port(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public AvailabilityGroupListenerImpl withExistingSqlVirtualMachineGroup(String resourceGroupName, String sqlVirtualMachineGroupName) { + this.resourceGroupName = resourceGroupName; + this.sqlVirtualMachineGroupName = sqlVirtualMachineGroupName; + return this; + } + + @Override + public AvailabilityGroupListenerImpl withAvailabilityGroupName(String availabilityGroupName) { + this.inner().withAvailabilityGroupName(availabilityGroupName); + return this; + } + + @Override + public AvailabilityGroupListenerImpl withCreateDefaultAvailabilityGroupIfNotExist(Boolean createDefaultAvailabilityGroupIfNotExist) { + this.inner().withCreateDefaultAvailabilityGroupIfNotExist(createDefaultAvailabilityGroupIfNotExist); + return this; + } + + @Override + public AvailabilityGroupListenerImpl withLoadBalancerConfigurations(List loadBalancerConfigurations) { + this.inner().withLoadBalancerConfigurations(loadBalancerConfigurations); + return this; + } + + @Override + public AvailabilityGroupListenerImpl withPort(Integer port) { + this.inner().withPort(port); + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenerInner.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenerInner.java new file mode 100644 index 0000000000000..d792e8f6bf632 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenerInner.java @@ -0,0 +1,141 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import java.util.List; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.LoadBalancerConfiguration; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.ProxyResource; + +/** + * A SQL Server availability group listener. + */ +@JsonFlatten +public class AvailabilityGroupListenerInner extends ProxyResource { + /** + * Provisioning state to track the async operation status. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * Name of the availability group. + */ + @JsonProperty(value = "properties.availabilityGroupName") + private String availabilityGroupName; + + /** + * List of load balancer configurations for an availability group listener. + */ + @JsonProperty(value = "properties.loadBalancerConfigurations") + private List loadBalancerConfigurations; + + /** + * Create a default availability group if it does not exist. + */ + @JsonProperty(value = "properties.createDefaultAvailabilityGroupIfNotExist") + private Boolean createDefaultAvailabilityGroupIfNotExist; + + /** + * Listener port. + */ + @JsonProperty(value = "properties.port") + private Integer port; + + /** + * Get provisioning state to track the async operation status. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + + /** + * Get name of the availability group. + * + * @return the availabilityGroupName value + */ + public String availabilityGroupName() { + return this.availabilityGroupName; + } + + /** + * Set name of the availability group. + * + * @param availabilityGroupName the availabilityGroupName value to set + * @return the AvailabilityGroupListenerInner object itself. + */ + public AvailabilityGroupListenerInner withAvailabilityGroupName(String availabilityGroupName) { + this.availabilityGroupName = availabilityGroupName; + return this; + } + + /** + * Get list of load balancer configurations for an availability group listener. + * + * @return the loadBalancerConfigurations value + */ + public List loadBalancerConfigurations() { + return this.loadBalancerConfigurations; + } + + /** + * Set list of load balancer configurations for an availability group listener. + * + * @param loadBalancerConfigurations the loadBalancerConfigurations value to set + * @return the AvailabilityGroupListenerInner object itself. + */ + public AvailabilityGroupListenerInner withLoadBalancerConfigurations(List loadBalancerConfigurations) { + this.loadBalancerConfigurations = loadBalancerConfigurations; + return this; + } + + /** + * Get create a default availability group if it does not exist. + * + * @return the createDefaultAvailabilityGroupIfNotExist value + */ + public Boolean createDefaultAvailabilityGroupIfNotExist() { + return this.createDefaultAvailabilityGroupIfNotExist; + } + + /** + * Set create a default availability group if it does not exist. + * + * @param createDefaultAvailabilityGroupIfNotExist the createDefaultAvailabilityGroupIfNotExist value to set + * @return the AvailabilityGroupListenerInner object itself. + */ + public AvailabilityGroupListenerInner withCreateDefaultAvailabilityGroupIfNotExist(Boolean createDefaultAvailabilityGroupIfNotExist) { + this.createDefaultAvailabilityGroupIfNotExist = createDefaultAvailabilityGroupIfNotExist; + return this; + } + + /** + * Get listener port. + * + * @return the port value + */ + public Integer port() { + return this.port; + } + + /** + * Set listener port. + * + * @param port the port value to set + * @return the AvailabilityGroupListenerInner object itself. + */ + public AvailabilityGroupListenerInner withPort(Integer port) { + this.port = port; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenersImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenersImpl.java new file mode 100644 index 0000000000000..c0b696454bcbe --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenersImpl.java @@ -0,0 +1,85 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListener; + +class AvailabilityGroupListenersImpl extends WrapperImpl implements AvailabilityGroupListeners { + private final SqlVirtualMachineManager manager; + + AvailabilityGroupListenersImpl(SqlVirtualMachineManager manager) { + super(manager.inner().availabilityGroupListeners()); + this.manager = manager; + } + + public SqlVirtualMachineManager manager() { + return this.manager; + } + + @Override + public AvailabilityGroupListenerImpl define(String name) { + return wrapModel(name); + } + + private AvailabilityGroupListenerImpl wrapModel(AvailabilityGroupListenerInner inner) { + return new AvailabilityGroupListenerImpl(inner, manager()); + } + + private AvailabilityGroupListenerImpl wrapModel(String name) { + return new AvailabilityGroupListenerImpl(name, this.manager()); + } + + @Override + public Observable listByGroupAsync(final String resourceGroupName, final String sqlVirtualMachineGroupName) { + AvailabilityGroupListenersInner client = this.inner(); + return client.listByGroupAsync(resourceGroupName, sqlVirtualMachineGroupName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public AvailabilityGroupListener call(AvailabilityGroupListenerInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + AvailabilityGroupListenersInner client = this.inner(); + return client.getAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName) + .flatMap(new Func1>() { + @Override + public Observable call(AvailabilityGroupListenerInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((AvailabilityGroupListener)wrapModel(inner)); + } + } + }); + } + + @Override + public Completable deleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + AvailabilityGroupListenersInner client = this.inner(); + return client.deleteAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName).toCompletable(); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenersInner.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenersInner.java new file mode 100644 index 0000000000000..a2c200244257e --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/AvailabilityGroupListenersInner.java @@ -0,0 +1,776 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in AvailabilityGroupListeners. + */ +public class AvailabilityGroupListenersInner { + /** The Retrofit service to perform REST calls. */ + private AvailabilityGroupListenersService service; + /** The service client containing this operation class. */ + private SqlVirtualMachineManagementClientImpl client; + + /** + * Initializes an instance of AvailabilityGroupListenersInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public AvailabilityGroupListenersInner(Retrofit retrofit, SqlVirtualMachineManagementClientImpl client) { + this.service = retrofit.create(AvailabilityGroupListenersService.class); + this.client = client; + } + + /** + * The interface defining all the services for AvailabilityGroupListeners to be + * used by Retrofit to perform actually REST calls. + */ + interface AvailabilityGroupListenersService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners get" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}") + Observable> get(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("availabilityGroupListenerName") String availabilityGroupListenerName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners createOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}") + Observable> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("availabilityGroupListenerName") String availabilityGroupListenerName, @Path("subscriptionId") String subscriptionId, @Body AvailabilityGroupListenerInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners beginCreateOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}") + Observable> beginCreateOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("availabilityGroupListenerName") String availabilityGroupListenerName, @Path("subscriptionId") String subscriptionId, @Body AvailabilityGroupListenerInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners delete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("availabilityGroupListenerName") String availabilityGroupListenerName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners beginDelete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("availabilityGroupListenerName") String availabilityGroupListenerName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners listByGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners") + Observable> listByGroup(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners listByGroupNext" }) + @GET + Observable> listByGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the AvailabilityGroupListenerInner object if successful. + */ + public AvailabilityGroupListenerInner get(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + return getWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName).toBlocking().single().body(); + } + + /** + * Gets an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName), serviceCallback); + } + + /** + * Gets an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AvailabilityGroupListenerInner object + */ + public Observable getAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + return getWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName).map(new Func1, AvailabilityGroupListenerInner>() { + @Override + public AvailabilityGroupListenerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AvailabilityGroupListenerInner object + */ + public Observable> getWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (availabilityGroupListenerName == null) { + throw new IllegalArgumentException("Parameter availabilityGroupListenerName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Creates or updates an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param parameters The availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the AvailabilityGroupListenerInner object if successful. + */ + public AvailabilityGroupListenerInner createOrUpdate(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, AvailabilityGroupListenerInner parameters) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, parameters).toBlocking().last().body(); + } + + /** + * Creates or updates an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param parameters The availability group listener. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, AvailabilityGroupListenerInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, parameters), serviceCallback); + } + + /** + * Creates or updates an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param parameters The availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, AvailabilityGroupListenerInner parameters) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, parameters).map(new Func1, AvailabilityGroupListenerInner>() { + @Override + public AvailabilityGroupListenerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param parameters The availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, AvailabilityGroupListenerInner parameters) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (availabilityGroupListenerName == null) { + throw new IllegalArgumentException("Parameter availabilityGroupListenerName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(parameters); + Observable> observable = service.createOrUpdate(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Creates or updates an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param parameters The availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the AvailabilityGroupListenerInner object if successful. + */ + public AvailabilityGroupListenerInner beginCreateOrUpdate(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, AvailabilityGroupListenerInner parameters) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, parameters).toBlocking().single().body(); + } + + /** + * Creates or updates an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param parameters The availability group listener. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, AvailabilityGroupListenerInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, parameters), serviceCallback); + } + + /** + * Creates or updates an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param parameters The availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AvailabilityGroupListenerInner object + */ + public Observable beginCreateOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, AvailabilityGroupListenerInner parameters) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, parameters).map(new Func1, AvailabilityGroupListenerInner>() { + @Override + public AvailabilityGroupListenerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param parameters The availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AvailabilityGroupListenerInner object + */ + public Observable> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, AvailabilityGroupListenerInner parameters) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (availabilityGroupListenerName == null) { + throw new IllegalArgumentException("Parameter availabilityGroupListenerName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(parameters); + return service.beginCreateOrUpdate(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateOrUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateOrUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName).toBlocking().last().body(); + } + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName), serviceCallback); + } + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + return deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (availabilityGroupListenerName == null) { + throw new IllegalArgumentException("Parameter availabilityGroupListenerName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName).toBlocking().single().body(); + } + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName), serviceCallback); + } + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + return beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes an availability group listener. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param availabilityGroupListenerName Name of the availability group listener. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, String availabilityGroupListenerName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (availabilityGroupListenerName == null) { + throw new IllegalArgumentException("Parameter availabilityGroupListenerName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(resourceGroupName, sqlVirtualMachineGroupName, availabilityGroupListenerName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<AvailabilityGroupListenerInner> object if successful. + */ + public PagedList listByGroup(final String resourceGroupName, final String sqlVirtualMachineGroupName) { + ServiceResponse> response = listByGroupSinglePageAsync(resourceGroupName, sqlVirtualMachineGroupName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByGroupAsync(final String resourceGroupName, final String sqlVirtualMachineGroupName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByGroupSinglePageAsync(resourceGroupName, sqlVirtualMachineGroupName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AvailabilityGroupListenerInner> object + */ + public Observable> listByGroupAsync(final String resourceGroupName, final String sqlVirtualMachineGroupName) { + return listByGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AvailabilityGroupListenerInner> object + */ + public Observable>> listByGroupWithServiceResponseAsync(final String resourceGroupName, final String sqlVirtualMachineGroupName) { + return listByGroupSinglePageAsync(resourceGroupName, sqlVirtualMachineGroupName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + ServiceResponse> * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + ServiceResponse> * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<AvailabilityGroupListenerInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByGroupSinglePageAsync(final String resourceGroupName, final String sqlVirtualMachineGroupName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByGroup(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<AvailabilityGroupListenerInner> object if successful. + */ + public PagedList listByGroupNext(final String nextPageLink) { + ServiceResponse> response = listByGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AvailabilityGroupListenerInner> object + */ + public Observable> listByGroupNextAsync(final String nextPageLink) { + return listByGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AvailabilityGroupListenerInner> object + */ + public Observable>> listByGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listByGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Lists all availability group listeners in a SQL virtual machine group. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<AvailabilityGroupListenerInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByGroupNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/IdParsingUtils.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/IdParsingUtils.java new file mode 100644 index 0000000000000..9c9b8833f90c8 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/IdParsingUtils.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; +import java.util.Arrays; +import java.util.Iterator; + +class IdParsingUtils { + public static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + public static String getValueFromIdByPosition(String id, int pos) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + int index = 0; + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (index == pos) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + index++; + } + return null; + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationImpl.java new file mode 100644 index 0000000000000..794374f8194fd --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationImpl.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.Operation; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.OperationDisplay; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.OperationOrigin; +import java.util.Map; + +class OperationImpl extends WrapperImpl implements Operation { + private final SqlVirtualMachineManager manager; + OperationImpl(OperationInner inner, SqlVirtualMachineManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public SqlVirtualMachineManager manager() { + return this.manager; + } + + @Override + public OperationDisplay display() { + return this.inner().display(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public OperationOrigin origin() { + return this.inner().origin(); + } + + @Override + public Map properties() { + return this.inner().properties(); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationInner.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationInner.java new file mode 100644 index 0000000000000..607ed9dd61848 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationInner.java @@ -0,0 +1,82 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.OperationDisplay; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.OperationOrigin; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * SQL REST API operation definition. + */ +public class OperationInner { + /** + * The name of the operation being performed on this particular object. + */ + @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY) + private String name; + + /** + * The localized display information for this particular operation / + * action. + */ + @JsonProperty(value = "display", access = JsonProperty.Access.WRITE_ONLY) + private OperationDisplay display; + + /** + * The intended executor of the operation. Possible values include: 'user', + * 'system'. + */ + @JsonProperty(value = "origin", access = JsonProperty.Access.WRITE_ONLY) + private OperationOrigin origin; + + /** + * Additional descriptions for the operation. + */ + @JsonProperty(value = "properties", access = JsonProperty.Access.WRITE_ONLY) + private Map properties; + + /** + * Get the name of the operation being performed on this particular object. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Get the localized display information for this particular operation / action. + * + * @return the display value + */ + public OperationDisplay display() { + return this.display; + } + + /** + * Get the intended executor of the operation. Possible values include: 'user', 'system'. + * + * @return the origin value + */ + public OperationOrigin origin() { + return this.origin; + } + + /** + * Get additional descriptions for the operation. + * + * @return the properties value + */ + public Map properties() { + return this.properties; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationsImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationsImpl.java new file mode 100644 index 0000000000000..79d67315bea7c --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationsImpl.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.Operations; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.Operation; + +class OperationsImpl extends WrapperImpl implements Operations { + private final SqlVirtualMachineManager manager; + + OperationsImpl(SqlVirtualMachineManager manager) { + super(manager.inner().operations()); + this.manager = manager; + } + + public SqlVirtualMachineManager manager() { + return this.manager; + } + + @Override + public Observable listAsync() { + OperationsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Operation call(OperationInner inner) { + return new OperationImpl(inner, manager()); + } + }); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationsInner.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationsInner.java new file mode 100644 index 0000000000000..b6c8ff825ff37 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/OperationsInner.java @@ -0,0 +1,283 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Operations. + */ +public class OperationsInner { + /** The Retrofit service to perform REST calls. */ + private OperationsService service; + /** The service client containing this operation class. */ + private SqlVirtualMachineManagementClientImpl client; + + /** + * Initializes an instance of OperationsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public OperationsInner(Retrofit retrofit, SqlVirtualMachineManagementClientImpl client) { + this.service = retrofit.create(OperationsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Operations to be + * used by Retrofit to perform actually REST calls. + */ + interface OperationsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.Operations list" }) + @GET("providers/Microsoft.SqlVirtualMachine/operations") + Observable> list(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.Operations listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<OperationInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<OperationInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<OperationInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<OperationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<OperationInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<OperationInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Lists all of the available SQL Rest API operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<OperationInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Lists all of the available SQL Rest API operations. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<OperationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/PageImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/PageImpl.java new file mode 100644 index 0000000000000..45180da2843b9 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/PageImpl.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.Page; +import java.util.List; + +/** + * An instance of this class defines a page of Azure resources and a link to + * get the next page of resources, if any. + * + * @param type of Azure resource + */ +public class PageImpl implements Page { + /** + * The link to the next page. + */ + @JsonProperty("nextLink") + private String nextPageLink; + + /** + * The list of items. + */ + @JsonProperty("value") + private List items; + + /** + * Gets the link to the next page. + * + * @return the link to the next page. + */ + @Override + public String nextPageLink() { + return this.nextPageLink; + } + + /** + * Gets the list of items. + * + * @return the list of items in {@link List}. + */ + @Override + public List items() { + return items; + } + + /** + * Sets the link to the next page. + * + * @param nextPageLink the link to the next page. + * @return this Page object itself. + */ + public PageImpl setNextPageLink(String nextPageLink) { + this.nextPageLink = nextPageLink; + return this; + } + + /** + * Sets the list of items. + * + * @param items the list of items in {@link List}. + * @return this Page object itself. + */ + public PageImpl setItems(List items) { + this.items = items; + return this; + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupImpl.java new file mode 100644 index 0000000000000..65b92d76f1754 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupImpl.java @@ -0,0 +1,104 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroup; +import rx.Observable; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVmGroupImageSku; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ScaleType; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ClusterManagerType; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ClusterConfiguration; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.WsfcDomainProfile; + +class SqlVirtualMachineGroupImpl extends GroupableResourceCoreImpl implements SqlVirtualMachineGroup, SqlVirtualMachineGroup.Definition, SqlVirtualMachineGroup.Update { + SqlVirtualMachineGroupImpl(String name, SqlVirtualMachineGroupInner inner, SqlVirtualMachineManager manager) { + super(name, inner, manager); + } + + @Override + public Observable createResourceAsync() { + SqlVirtualMachineGroupsInner client = this.manager().inner().sqlVirtualMachineGroups(); + return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + SqlVirtualMachineGroupsInner client = this.manager().inner().sqlVirtualMachineGroups(); + return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + SqlVirtualMachineGroupsInner client = this.manager().inner().sqlVirtualMachineGroups(); + return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + + @Override + public ClusterConfiguration clusterConfiguration() { + return this.inner().clusterConfiguration(); + } + + @Override + public ClusterManagerType clusterManagerType() { + return this.inner().clusterManagerType(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public ScaleType scaleType() { + return this.inner().scaleType(); + } + + @Override + public String sqlImageOffer() { + return this.inner().sqlImageOffer(); + } + + @Override + public SqlVmGroupImageSku sqlImageSku() { + return this.inner().sqlImageSku(); + } + + @Override + public WsfcDomainProfile wsfcDomainProfile() { + return this.inner().wsfcDomainProfile(); + } + + @Override + public SqlVirtualMachineGroupImpl withSqlImageOffer(String sqlImageOffer) { + this.inner().withSqlImageOffer(sqlImageOffer); + return this; + } + + @Override + public SqlVirtualMachineGroupImpl withSqlImageSku(SqlVmGroupImageSku sqlImageSku) { + this.inner().withSqlImageSku(sqlImageSku); + return this; + } + + @Override + public SqlVirtualMachineGroupImpl withWsfcDomainProfile(WsfcDomainProfile wsfcDomainProfile) { + this.inner().withWsfcDomainProfile(wsfcDomainProfile); + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupInner.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupInner.java new file mode 100644 index 0000000000000..0732ac1d959ec --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupInner.java @@ -0,0 +1,165 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVmGroupImageSku; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ScaleType; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ClusterManagerType; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ClusterConfiguration; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.WsfcDomainProfile; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * A SQL virtual machine group. + */ +@JsonFlatten +public class SqlVirtualMachineGroupInner extends Resource { + /** + * Provisioning state to track the async operation status. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * SQL image offer. Examples may include SQL2016-WS2016, SQL2017-WS2016. + */ + @JsonProperty(value = "properties.sqlImageOffer") + private String sqlImageOffer; + + /** + * SQL image sku. Possible values include: 'Developer', 'Enterprise'. + */ + @JsonProperty(value = "properties.sqlImageSku") + private SqlVmGroupImageSku sqlImageSku; + + /** + * Scale type. Possible values include: 'HA'. + */ + @JsonProperty(value = "properties.scaleType", access = JsonProperty.Access.WRITE_ONLY) + private ScaleType scaleType; + + /** + * Type of cluster manager: Windows Server Failover Cluster (WSFC), implied + * by the scale type of the group and the OS type. Possible values include: + * 'WSFC'. + */ + @JsonProperty(value = "properties.clusterManagerType", access = JsonProperty.Access.WRITE_ONLY) + private ClusterManagerType clusterManagerType; + + /** + * Cluster type. Possible values include: 'Domainful'. + */ + @JsonProperty(value = "properties.clusterConfiguration", access = JsonProperty.Access.WRITE_ONLY) + private ClusterConfiguration clusterConfiguration; + + /** + * Cluster Active Directory domain profile. + */ + @JsonProperty(value = "properties.wsfcDomainProfile") + private WsfcDomainProfile wsfcDomainProfile; + + /** + * Get provisioning state to track the async operation status. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + + /** + * Get sQL image offer. Examples may include SQL2016-WS2016, SQL2017-WS2016. + * + * @return the sqlImageOffer value + */ + public String sqlImageOffer() { + return this.sqlImageOffer; + } + + /** + * Set sQL image offer. Examples may include SQL2016-WS2016, SQL2017-WS2016. + * + * @param sqlImageOffer the sqlImageOffer value to set + * @return the SqlVirtualMachineGroupInner object itself. + */ + public SqlVirtualMachineGroupInner withSqlImageOffer(String sqlImageOffer) { + this.sqlImageOffer = sqlImageOffer; + return this; + } + + /** + * Get sQL image sku. Possible values include: 'Developer', 'Enterprise'. + * + * @return the sqlImageSku value + */ + public SqlVmGroupImageSku sqlImageSku() { + return this.sqlImageSku; + } + + /** + * Set sQL image sku. Possible values include: 'Developer', 'Enterprise'. + * + * @param sqlImageSku the sqlImageSku value to set + * @return the SqlVirtualMachineGroupInner object itself. + */ + public SqlVirtualMachineGroupInner withSqlImageSku(SqlVmGroupImageSku sqlImageSku) { + this.sqlImageSku = sqlImageSku; + return this; + } + + /** + * Get scale type. Possible values include: 'HA'. + * + * @return the scaleType value + */ + public ScaleType scaleType() { + return this.scaleType; + } + + /** + * Get type of cluster manager: Windows Server Failover Cluster (WSFC), implied by the scale type of the group and the OS type. Possible values include: 'WSFC'. + * + * @return the clusterManagerType value + */ + public ClusterManagerType clusterManagerType() { + return this.clusterManagerType; + } + + /** + * Get cluster type. Possible values include: 'Domainful'. + * + * @return the clusterConfiguration value + */ + public ClusterConfiguration clusterConfiguration() { + return this.clusterConfiguration; + } + + /** + * Get cluster Active Directory domain profile. + * + * @return the wsfcDomainProfile value + */ + public WsfcDomainProfile wsfcDomainProfile() { + return this.wsfcDomainProfile; + } + + /** + * Set cluster Active Directory domain profile. + * + * @param wsfcDomainProfile the wsfcDomainProfile value to set + * @return the SqlVirtualMachineGroupInner object itself. + */ + public SqlVirtualMachineGroupInner withWsfcDomainProfile(WsfcDomainProfile wsfcDomainProfile) { + this.wsfcDomainProfile = wsfcDomainProfile; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupsImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupsImpl.java new file mode 100644 index 0000000000000..f3e502ef1b960 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupsImpl.java @@ -0,0 +1,138 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * def + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.arm.resources.collection.implementation.GroupableResourcesCoreImpl; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroup; +import rx.Observable; +import rx.Completable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import com.microsoft.azure.arm.resources.ResourceUtilsCore; +import com.microsoft.azure.arm.utils.RXMapper; +import rx.functions.Func1; +import com.microsoft.azure.PagedList; +import com.microsoft.azure.Page; + +class SqlVirtualMachineGroupsImpl extends GroupableResourcesCoreImpl implements SqlVirtualMachineGroups { + protected SqlVirtualMachineGroupsImpl(SqlVirtualMachineManager manager) { + super(manager.inner().sqlVirtualMachineGroups(), manager); + } + + @Override + protected Observable getInnerAsync(String resourceGroupName, String name) { + SqlVirtualMachineGroupsInner client = this.inner(); + return client.getByResourceGroupAsync(resourceGroupName, name); + } + + @Override + protected Completable deleteInnerAsync(String resourceGroupName, String name) { + SqlVirtualMachineGroupsInner client = this.inner(); + return client.deleteAsync(resourceGroupName, name).toCompletable(); + } + + @Override + public Observable deleteByIdsAsync(Collection ids) { + if (ids == null || ids.isEmpty()) { + return Observable.empty(); + } + Collection> observables = new ArrayList<>(); + for (String id : ids) { + final String resourceGroupName = ResourceUtilsCore.groupFromResourceId(id); + final String name = ResourceUtilsCore.nameFromResourceId(id); + Observable o = RXMapper.map(this.inner().deleteAsync(resourceGroupName, name), id); + observables.add(o); + } + return Observable.mergeDelayError(observables); + } + + @Override + public Observable deleteByIdsAsync(String...ids) { + return this.deleteByIdsAsync(new ArrayList(Arrays.asList(ids))); + } + + @Override + public void deleteByIds(Collection ids) { + if (ids != null && !ids.isEmpty()) { + this.deleteByIdsAsync(ids).toBlocking().last(); + } + } + + @Override + public void deleteByIds(String...ids) { + this.deleteByIds(new ArrayList(Arrays.asList(ids))); + } + + @Override + public PagedList listByResourceGroup(String resourceGroupName) { + SqlVirtualMachineGroupsInner client = this.inner(); + return this.wrapList(client.listByResourceGroup(resourceGroupName)); + } + + @Override + public Observable listByResourceGroupAsync(String resourceGroupName) { + SqlVirtualMachineGroupsInner client = this.inner(); + return client.listByResourceGroupAsync(resourceGroupName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public SqlVirtualMachineGroup call(SqlVirtualMachineGroupInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public PagedList list() { + SqlVirtualMachineGroupsInner client = this.inner(); + return this.wrapList(client.list()); + } + + @Override + public Observable listAsync() { + SqlVirtualMachineGroupsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public SqlVirtualMachineGroup call(SqlVirtualMachineGroupInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public SqlVirtualMachineGroupImpl define(String name) { + return wrapModel(name); + } + + @Override + protected SqlVirtualMachineGroupImpl wrapModel(SqlVirtualMachineGroupInner inner) { + return new SqlVirtualMachineGroupImpl(inner.name(), inner, manager()); + } + + @Override + protected SqlVirtualMachineGroupImpl wrapModel(String name) { + return new SqlVirtualMachineGroupImpl(name, new SqlVirtualMachineGroupInner(), this.manager()); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupsInner.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupsInner.java new file mode 100644 index 0000000000000..8978c000569da --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineGroupsInner.java @@ -0,0 +1,1295 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.arm.collection.InnerSupportsGet; +import com.microsoft.azure.arm.collection.InnerSupportsDelete; +import com.microsoft.azure.arm.collection.InnerSupportsListing; +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroupUpdate; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in SqlVirtualMachineGroups. + */ +public class SqlVirtualMachineGroupsInner implements InnerSupportsGet, InnerSupportsDelete, InnerSupportsListing { + /** The Retrofit service to perform REST calls. */ + private SqlVirtualMachineGroupsService service; + /** The service client containing this operation class. */ + private SqlVirtualMachineManagementClientImpl client; + + /** + * Initializes an instance of SqlVirtualMachineGroupsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public SqlVirtualMachineGroupsInner(Retrofit retrofit, SqlVirtualMachineManagementClientImpl client) { + this.service = retrofit.create(SqlVirtualMachineGroupsService.class); + this.client = client; + } + + /** + * The interface defining all the services for SqlVirtualMachineGroups to be + * used by Retrofit to perform actually REST calls. + */ + interface SqlVirtualMachineGroupsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups getByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}") + Observable> getByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups createOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}") + Observable> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("subscriptionId") String subscriptionId, @Body SqlVirtualMachineGroupInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups beginCreateOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}") + Observable> beginCreateOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("subscriptionId") String subscriptionId, @Body SqlVirtualMachineGroupInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups delete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups beginDelete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups update" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}") + Observable> update(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SqlVirtualMachineGroupUpdate parameters, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups beginUpdate" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}") + Observable> beginUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineGroupName") String sqlVirtualMachineGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SqlVirtualMachineGroupUpdate parameters, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups listByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups") + Observable> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups list" }) + @GET("subscriptions/{subscriptionId}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups") + Observable> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups listByResourceGroupNext" }) + @GET + Observable> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineGroupInner object if successful. + */ + public SqlVirtualMachineGroupInner getByResourceGroup(String resourceGroupName, String sqlVirtualMachineGroupName) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).toBlocking().single().body(); + } + + /** + * Gets a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getByResourceGroupAsync(String resourceGroupName, String sqlVirtualMachineGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName), serviceCallback); + } + + /** + * Gets a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineGroupInner object + */ + public Observable getByResourceGroupAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).map(new Func1, SqlVirtualMachineGroupInner>() { + @Override + public SqlVirtualMachineGroupInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineGroupInner object + */ + public Observable> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.getByResourceGroup(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getByResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getByResourceGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Creates or updates a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param parameters The SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineGroupInner object if successful. + */ + public SqlVirtualMachineGroupInner createOrUpdate(String resourceGroupName, String sqlVirtualMachineGroupName, SqlVirtualMachineGroupInner parameters) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, parameters).toBlocking().last().body(); + } + + /** + * Creates or updates a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param parameters The SQL virtual machine group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, SqlVirtualMachineGroupInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, parameters), serviceCallback); + } + + /** + * Creates or updates a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param parameters The SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, SqlVirtualMachineGroupInner parameters) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, parameters).map(new Func1, SqlVirtualMachineGroupInner>() { + @Override + public SqlVirtualMachineGroupInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param parameters The SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, SqlVirtualMachineGroupInner parameters) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(parameters); + Observable> observable = service.createOrUpdate(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Creates or updates a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param parameters The SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineGroupInner object if successful. + */ + public SqlVirtualMachineGroupInner beginCreateOrUpdate(String resourceGroupName, String sqlVirtualMachineGroupName, SqlVirtualMachineGroupInner parameters) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, parameters).toBlocking().single().body(); + } + + /** + * Creates or updates a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param parameters The SQL virtual machine group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, SqlVirtualMachineGroupInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, parameters), serviceCallback); + } + + /** + * Creates or updates a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param parameters The SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineGroupInner object + */ + public Observable beginCreateOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, SqlVirtualMachineGroupInner parameters) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, parameters).map(new Func1, SqlVirtualMachineGroupInner>() { + @Override + public SqlVirtualMachineGroupInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param parameters The SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineGroupInner object + */ + public Observable> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, SqlVirtualMachineGroupInner parameters) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(parameters); + return service.beginCreateOrUpdate(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateOrUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateOrUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Deletes a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String resourceGroupName, String sqlVirtualMachineGroupName) { + deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).toBlocking().last().body(); + } + + /** + * Deletes a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName), serviceCallback); + } + + /** + * Deletes a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + return deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Deletes a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String resourceGroupName, String sqlVirtualMachineGroupName) { + beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).toBlocking().single().body(); + } + + /** + * Deletes a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName), serviceCallback); + } + + /** + * Deletes a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + return beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes a SQL virtual machine group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineGroupInner object if successful. + */ + public SqlVirtualMachineGroupInner update(String resourceGroupName, String sqlVirtualMachineGroupName) { + return updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).toBlocking().last().body(); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName), serviceCallback); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + return updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).map(new Func1, SqlVirtualMachineGroupInner>() { + @Override + public SqlVirtualMachineGroupInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final Map tags = null; + SqlVirtualMachineGroupUpdate parameters = new SqlVirtualMachineGroupUpdate(); + parameters.withTags(null); + Observable> observable = service.update(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineGroupInner object if successful. + */ + public SqlVirtualMachineGroupInner update(String resourceGroupName, String sqlVirtualMachineGroupName, Map tags) { + return updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, tags).toBlocking().last().body(); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param tags Resource tags. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, tags), serviceCallback); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, Map tags) { + return updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, tags).map(new Func1, SqlVirtualMachineGroupInner>() { + @Override + public SqlVirtualMachineGroupInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, Map tags) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(tags); + SqlVirtualMachineGroupUpdate parameters = new SqlVirtualMachineGroupUpdate(); + parameters.withTags(tags); + Observable> observable = service.update(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineGroupInner object if successful. + */ + public SqlVirtualMachineGroupInner beginUpdate(String resourceGroupName, String sqlVirtualMachineGroupName) { + return beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).toBlocking().single().body(); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName), serviceCallback); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineGroupInner object + */ + public Observable beginUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + return beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName).map(new Func1, SqlVirtualMachineGroupInner>() { + @Override + public SqlVirtualMachineGroupInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineGroupInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final Map tags = null; + SqlVirtualMachineGroupUpdate parameters = new SqlVirtualMachineGroupUpdate(); + parameters.withTags(null); + return service.beginUpdate(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineGroupInner object if successful. + */ + public SqlVirtualMachineGroupInner beginUpdate(String resourceGroupName, String sqlVirtualMachineGroupName, Map tags) { + return beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, tags).toBlocking().single().body(); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param tags Resource tags. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, tags), serviceCallback); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineGroupInner object + */ + public Observable beginUpdateAsync(String resourceGroupName, String sqlVirtualMachineGroupName, Map tags) { + return beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineGroupName, tags).map(new Func1, SqlVirtualMachineGroupInner>() { + @Override + public SqlVirtualMachineGroupInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates SQL virtual machine group tags. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineGroupName Name of the SQL virtual machine group. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineGroupInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineGroupName, Map tags) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineGroupName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(tags); + SqlVirtualMachineGroupUpdate parameters = new SqlVirtualMachineGroupUpdate(); + parameters.withTags(tags); + return service.beginUpdate(resourceGroupName, sqlVirtualMachineGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SqlVirtualMachineGroupInner> object if successful. + */ + public PagedList listByResourceGroup(final String resourceGroupName) { + ServiceResponse> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupSinglePageAsync(resourceGroupName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineGroupInner> object + */ + public Observable> listByResourceGroupAsync(final String resourceGroupName) { + return listByResourceGroupWithServiceResponseAsync(resourceGroupName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineGroupInner> object + */ + public Observable>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) { + return listByResourceGroupSinglePageAsync(resourceGroupName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + ServiceResponse> * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SqlVirtualMachineGroupInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupSinglePageAsync(final String resourceGroupName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SqlVirtualMachineGroupInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineGroupInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineGroupInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SqlVirtualMachineGroupInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SqlVirtualMachineGroupInner> object if successful. + */ + public PagedList listByResourceGroupNext(final String nextPageLink) { + ServiceResponse> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineGroupInner> object + */ + public Observable> listByResourceGroupNextAsync(final String nextPageLink) { + return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineGroupInner> object + */ + public Observable>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all SQL virtual machine groups in a resource group. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SqlVirtualMachineGroupInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SqlVirtualMachineGroupInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineGroupInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineGroupInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all SQL virtual machine groups in a subscription. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SqlVirtualMachineGroupInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineImpl.java new file mode 100644 index 0000000000000..6cbd713dff1b3 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineImpl.java @@ -0,0 +1,192 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachine; +import rx.Observable; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ResourceIdentity; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlServerLicenseType; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlManagementMode; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlImageSku; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.WsfcDomainCredentials; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AutoPatchingSettings; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AutoBackupSettings; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.KeyVaultCredentialSettings; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ServerConfigurationsManagementSettings; + +class SqlVirtualMachineImpl extends GroupableResourceCoreImpl implements SqlVirtualMachine, SqlVirtualMachine.Definition, SqlVirtualMachine.Update { + SqlVirtualMachineImpl(String name, SqlVirtualMachineInner inner, SqlVirtualMachineManager manager) { + super(name, inner, manager); + } + + @Override + public Observable createResourceAsync() { + SqlVirtualMachinesInner client = this.manager().inner().sqlVirtualMachines(); + return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + SqlVirtualMachinesInner client = this.manager().inner().sqlVirtualMachines(); + return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + SqlVirtualMachinesInner client = this.manager().inner().sqlVirtualMachines(); + return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + + @Override + public AutoBackupSettings autoBackupSettings() { + return this.inner().autoBackupSettings(); + } + + @Override + public AutoPatchingSettings autoPatchingSettings() { + return this.inner().autoPatchingSettings(); + } + + @Override + public ResourceIdentity identity() { + return this.inner().identity(); + } + + @Override + public KeyVaultCredentialSettings keyVaultCredentialSettings() { + return this.inner().keyVaultCredentialSettings(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public ServerConfigurationsManagementSettings serverConfigurationsManagementSettings() { + return this.inner().serverConfigurationsManagementSettings(); + } + + @Override + public String sqlImageOffer() { + return this.inner().sqlImageOffer(); + } + + @Override + public SqlImageSku sqlImageSku() { + return this.inner().sqlImageSku(); + } + + @Override + public SqlManagementMode sqlManagement() { + return this.inner().sqlManagement(); + } + + @Override + public SqlServerLicenseType sqlServerLicenseType() { + return this.inner().sqlServerLicenseType(); + } + + @Override + public String sqlVirtualMachineGroupResourceId() { + return this.inner().sqlVirtualMachineGroupResourceId(); + } + + @Override + public String virtualMachineResourceId() { + return this.inner().virtualMachineResourceId(); + } + + @Override + public WsfcDomainCredentials wsfcDomainCredentials() { + return this.inner().wsfcDomainCredentials(); + } + + @Override + public SqlVirtualMachineImpl withAutoBackupSettings(AutoBackupSettings autoBackupSettings) { + this.inner().withAutoBackupSettings(autoBackupSettings); + return this; + } + + @Override + public SqlVirtualMachineImpl withAutoPatchingSettings(AutoPatchingSettings autoPatchingSettings) { + this.inner().withAutoPatchingSettings(autoPatchingSettings); + return this; + } + + @Override + public SqlVirtualMachineImpl withIdentity(ResourceIdentity identity) { + this.inner().withIdentity(identity); + return this; + } + + @Override + public SqlVirtualMachineImpl withKeyVaultCredentialSettings(KeyVaultCredentialSettings keyVaultCredentialSettings) { + this.inner().withKeyVaultCredentialSettings(keyVaultCredentialSettings); + return this; + } + + @Override + public SqlVirtualMachineImpl withServerConfigurationsManagementSettings(ServerConfigurationsManagementSettings serverConfigurationsManagementSettings) { + this.inner().withServerConfigurationsManagementSettings(serverConfigurationsManagementSettings); + return this; + } + + @Override + public SqlVirtualMachineImpl withSqlImageOffer(String sqlImageOffer) { + this.inner().withSqlImageOffer(sqlImageOffer); + return this; + } + + @Override + public SqlVirtualMachineImpl withSqlImageSku(SqlImageSku sqlImageSku) { + this.inner().withSqlImageSku(sqlImageSku); + return this; + } + + @Override + public SqlVirtualMachineImpl withSqlManagement(SqlManagementMode sqlManagement) { + this.inner().withSqlManagement(sqlManagement); + return this; + } + + @Override + public SqlVirtualMachineImpl withSqlServerLicenseType(SqlServerLicenseType sqlServerLicenseType) { + this.inner().withSqlServerLicenseType(sqlServerLicenseType); + return this; + } + + @Override + public SqlVirtualMachineImpl withSqlVirtualMachineGroupResourceId(String sqlVirtualMachineGroupResourceId) { + this.inner().withSqlVirtualMachineGroupResourceId(sqlVirtualMachineGroupResourceId); + return this; + } + + @Override + public SqlVirtualMachineImpl withVirtualMachineResourceId(String virtualMachineResourceId) { + this.inner().withVirtualMachineResourceId(virtualMachineResourceId); + return this; + } + + @Override + public SqlVirtualMachineImpl withWsfcDomainCredentials(WsfcDomainCredentials wsfcDomainCredentials) { + this.inner().withWsfcDomainCredentials(wsfcDomainCredentials); + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineInner.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineInner.java new file mode 100644 index 0000000000000..7448ec5c2ab64 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineInner.java @@ -0,0 +1,362 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ResourceIdentity; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlServerLicenseType; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlManagementMode; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlImageSku; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.WsfcDomainCredentials; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AutoPatchingSettings; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AutoBackupSettings; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.KeyVaultCredentialSettings; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.ServerConfigurationsManagementSettings; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * A SQL virtual machine. + */ +@JsonFlatten +public class SqlVirtualMachineInner extends Resource { + /** + * Azure Active Directory identity of the server. + */ + @JsonProperty(value = "identity") + private ResourceIdentity identity; + + /** + * ARM Resource id of underlying virtual machine created from SQL + * marketplace image. + */ + @JsonProperty(value = "properties.virtualMachineResourceId") + private String virtualMachineResourceId; + + /** + * Provisioning state to track the async operation status. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * SQL image offer. Examples include SQL2016-WS2016, SQL2017-WS2016. + */ + @JsonProperty(value = "properties.sqlImageOffer") + private String sqlImageOffer; + + /** + * SQL Server license type. Possible values include: 'PAYG', 'AHUB'. + */ + @JsonProperty(value = "properties.sqlServerLicenseType") + private SqlServerLicenseType sqlServerLicenseType; + + /** + * SQL Server Management type. Possible values include: 'Full', + * 'LightWeight', 'NoAgent'. + */ + @JsonProperty(value = "properties.sqlManagement") + private SqlManagementMode sqlManagement; + + /** + * SQL Server edition type. Possible values include: 'Developer', + * 'Express', 'Standard', 'Enterprise', 'Web'. + */ + @JsonProperty(value = "properties.sqlImageSku") + private SqlImageSku sqlImageSku; + + /** + * ARM resource id of the SQL virtual machine group this SQL virtual + * machine is or will be part of. + */ + @JsonProperty(value = "properties.sqlVirtualMachineGroupResourceId") + private String sqlVirtualMachineGroupResourceId; + + /** + * Domain credentials for setting up Windows Server Failover Cluster for + * SQL availability group. + */ + @JsonProperty(value = "properties.wsfcDomainCredentials") + private WsfcDomainCredentials wsfcDomainCredentials; + + /** + * Auto patching settings for applying critical security updates to SQL + * virtual machine. + */ + @JsonProperty(value = "properties.autoPatchingSettings") + private AutoPatchingSettings autoPatchingSettings; + + /** + * Auto backup settings for SQL Server. + */ + @JsonProperty(value = "properties.autoBackupSettings") + private AutoBackupSettings autoBackupSettings; + + /** + * Key vault credential settings. + */ + @JsonProperty(value = "properties.keyVaultCredentialSettings") + private KeyVaultCredentialSettings keyVaultCredentialSettings; + + /** + * SQL Server configuration management settings. + */ + @JsonProperty(value = "properties.serverConfigurationsManagementSettings") + private ServerConfigurationsManagementSettings serverConfigurationsManagementSettings; + + /** + * Get azure Active Directory identity of the server. + * + * @return the identity value + */ + public ResourceIdentity identity() { + return this.identity; + } + + /** + * Set azure Active Directory identity of the server. + * + * @param identity the identity value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withIdentity(ResourceIdentity identity) { + this.identity = identity; + return this; + } + + /** + * Get aRM Resource id of underlying virtual machine created from SQL marketplace image. + * + * @return the virtualMachineResourceId value + */ + public String virtualMachineResourceId() { + return this.virtualMachineResourceId; + } + + /** + * Set aRM Resource id of underlying virtual machine created from SQL marketplace image. + * + * @param virtualMachineResourceId the virtualMachineResourceId value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withVirtualMachineResourceId(String virtualMachineResourceId) { + this.virtualMachineResourceId = virtualMachineResourceId; + return this; + } + + /** + * Get provisioning state to track the async operation status. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + + /** + * Get sQL image offer. Examples include SQL2016-WS2016, SQL2017-WS2016. + * + * @return the sqlImageOffer value + */ + public String sqlImageOffer() { + return this.sqlImageOffer; + } + + /** + * Set sQL image offer. Examples include SQL2016-WS2016, SQL2017-WS2016. + * + * @param sqlImageOffer the sqlImageOffer value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withSqlImageOffer(String sqlImageOffer) { + this.sqlImageOffer = sqlImageOffer; + return this; + } + + /** + * Get sQL Server license type. Possible values include: 'PAYG', 'AHUB'. + * + * @return the sqlServerLicenseType value + */ + public SqlServerLicenseType sqlServerLicenseType() { + return this.sqlServerLicenseType; + } + + /** + * Set sQL Server license type. Possible values include: 'PAYG', 'AHUB'. + * + * @param sqlServerLicenseType the sqlServerLicenseType value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withSqlServerLicenseType(SqlServerLicenseType sqlServerLicenseType) { + this.sqlServerLicenseType = sqlServerLicenseType; + return this; + } + + /** + * Get sQL Server Management type. Possible values include: 'Full', 'LightWeight', 'NoAgent'. + * + * @return the sqlManagement value + */ + public SqlManagementMode sqlManagement() { + return this.sqlManagement; + } + + /** + * Set sQL Server Management type. Possible values include: 'Full', 'LightWeight', 'NoAgent'. + * + * @param sqlManagement the sqlManagement value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withSqlManagement(SqlManagementMode sqlManagement) { + this.sqlManagement = sqlManagement; + return this; + } + + /** + * Get sQL Server edition type. Possible values include: 'Developer', 'Express', 'Standard', 'Enterprise', 'Web'. + * + * @return the sqlImageSku value + */ + public SqlImageSku sqlImageSku() { + return this.sqlImageSku; + } + + /** + * Set sQL Server edition type. Possible values include: 'Developer', 'Express', 'Standard', 'Enterprise', 'Web'. + * + * @param sqlImageSku the sqlImageSku value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withSqlImageSku(SqlImageSku sqlImageSku) { + this.sqlImageSku = sqlImageSku; + return this; + } + + /** + * Get aRM resource id of the SQL virtual machine group this SQL virtual machine is or will be part of. + * + * @return the sqlVirtualMachineGroupResourceId value + */ + public String sqlVirtualMachineGroupResourceId() { + return this.sqlVirtualMachineGroupResourceId; + } + + /** + * Set aRM resource id of the SQL virtual machine group this SQL virtual machine is or will be part of. + * + * @param sqlVirtualMachineGroupResourceId the sqlVirtualMachineGroupResourceId value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withSqlVirtualMachineGroupResourceId(String sqlVirtualMachineGroupResourceId) { + this.sqlVirtualMachineGroupResourceId = sqlVirtualMachineGroupResourceId; + return this; + } + + /** + * Get domain credentials for setting up Windows Server Failover Cluster for SQL availability group. + * + * @return the wsfcDomainCredentials value + */ + public WsfcDomainCredentials wsfcDomainCredentials() { + return this.wsfcDomainCredentials; + } + + /** + * Set domain credentials for setting up Windows Server Failover Cluster for SQL availability group. + * + * @param wsfcDomainCredentials the wsfcDomainCredentials value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withWsfcDomainCredentials(WsfcDomainCredentials wsfcDomainCredentials) { + this.wsfcDomainCredentials = wsfcDomainCredentials; + return this; + } + + /** + * Get auto patching settings for applying critical security updates to SQL virtual machine. + * + * @return the autoPatchingSettings value + */ + public AutoPatchingSettings autoPatchingSettings() { + return this.autoPatchingSettings; + } + + /** + * Set auto patching settings for applying critical security updates to SQL virtual machine. + * + * @param autoPatchingSettings the autoPatchingSettings value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withAutoPatchingSettings(AutoPatchingSettings autoPatchingSettings) { + this.autoPatchingSettings = autoPatchingSettings; + return this; + } + + /** + * Get auto backup settings for SQL Server. + * + * @return the autoBackupSettings value + */ + public AutoBackupSettings autoBackupSettings() { + return this.autoBackupSettings; + } + + /** + * Set auto backup settings for SQL Server. + * + * @param autoBackupSettings the autoBackupSettings value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withAutoBackupSettings(AutoBackupSettings autoBackupSettings) { + this.autoBackupSettings = autoBackupSettings; + return this; + } + + /** + * Get key vault credential settings. + * + * @return the keyVaultCredentialSettings value + */ + public KeyVaultCredentialSettings keyVaultCredentialSettings() { + return this.keyVaultCredentialSettings; + } + + /** + * Set key vault credential settings. + * + * @param keyVaultCredentialSettings the keyVaultCredentialSettings value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withKeyVaultCredentialSettings(KeyVaultCredentialSettings keyVaultCredentialSettings) { + this.keyVaultCredentialSettings = keyVaultCredentialSettings; + return this; + } + + /** + * Get sQL Server configuration management settings. + * + * @return the serverConfigurationsManagementSettings value + */ + public ServerConfigurationsManagementSettings serverConfigurationsManagementSettings() { + return this.serverConfigurationsManagementSettings; + } + + /** + * Set sQL Server configuration management settings. + * + * @param serverConfigurationsManagementSettings the serverConfigurationsManagementSettings value to set + * @return the SqlVirtualMachineInner object itself. + */ + public SqlVirtualMachineInner withServerConfigurationsManagementSettings(ServerConfigurationsManagementSettings serverConfigurationsManagementSettings) { + this.serverConfigurationsManagementSettings = serverConfigurationsManagementSettings; + return this; + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineManagementClientImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineManagementClientImpl.java new file mode 100644 index 0000000000000..529c508c8c780 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineManagementClientImpl.java @@ -0,0 +1,238 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.AzureClient; +import com.microsoft.azure.AzureServiceClient; +import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.microsoft.rest.RestClient; + +/** + * Initializes a new instance of the SqlVirtualMachineManagementClientImpl class. + */ +public class SqlVirtualMachineManagementClientImpl extends AzureServiceClient { + /** the {@link AzureClient} used for long running operations. */ + private AzureClient azureClient; + + /** + * Gets the {@link AzureClient} used for long running operations. + * @return the azure client; + */ + public AzureClient getAzureClient() { + return this.azureClient; + } + + /** Subscription ID that identifies an Azure subscription. */ + private String subscriptionId; + + /** + * Gets Subscription ID that identifies an Azure subscription. + * + * @return the subscriptionId value. + */ + public String subscriptionId() { + return this.subscriptionId; + } + + /** + * Sets Subscription ID that identifies an Azure subscription. + * + * @param subscriptionId the subscriptionId value. + * @return the service client itself + */ + public SqlVirtualMachineManagementClientImpl withSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /** API version to use for the request. */ + private String apiVersion; + + /** + * Gets API version to use for the request. + * + * @return the apiVersion value. + */ + public String apiVersion() { + return this.apiVersion; + } + + /** The preferred language for the response. */ + private String acceptLanguage; + + /** + * Gets The preferred language for the response. + * + * @return the acceptLanguage value. + */ + public String acceptLanguage() { + return this.acceptLanguage; + } + + /** + * Sets The preferred language for the response. + * + * @param acceptLanguage the acceptLanguage value. + * @return the service client itself + */ + public SqlVirtualMachineManagementClientImpl withAcceptLanguage(String acceptLanguage) { + this.acceptLanguage = acceptLanguage; + return this; + } + + /** The retry timeout in seconds for Long Running Operations. Default value is 30. */ + private int longRunningOperationRetryTimeout; + + /** + * Gets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @return the longRunningOperationRetryTimeout value. + */ + public int longRunningOperationRetryTimeout() { + return this.longRunningOperationRetryTimeout; + } + + /** + * Sets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. + * @return the service client itself + */ + public SqlVirtualMachineManagementClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { + this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; + return this; + } + + /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ + private boolean generateClientRequestId; + + /** + * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @return the generateClientRequestId value. + */ + public boolean generateClientRequestId() { + return this.generateClientRequestId; + } + + /** + * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @param generateClientRequestId the generateClientRequestId value. + * @return the service client itself + */ + public SqlVirtualMachineManagementClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { + this.generateClientRequestId = generateClientRequestId; + return this; + } + + /** + * The AvailabilityGroupListenersInner object to access its operations. + */ + private AvailabilityGroupListenersInner availabilityGroupListeners; + + /** + * Gets the AvailabilityGroupListenersInner object to access its operations. + * @return the AvailabilityGroupListenersInner object. + */ + public AvailabilityGroupListenersInner availabilityGroupListeners() { + return this.availabilityGroupListeners; + } + + /** + * The OperationsInner object to access its operations. + */ + private OperationsInner operations; + + /** + * Gets the OperationsInner object to access its operations. + * @return the OperationsInner object. + */ + public OperationsInner operations() { + return this.operations; + } + + /** + * The SqlVirtualMachineGroupsInner object to access its operations. + */ + private SqlVirtualMachineGroupsInner sqlVirtualMachineGroups; + + /** + * Gets the SqlVirtualMachineGroupsInner object to access its operations. + * @return the SqlVirtualMachineGroupsInner object. + */ + public SqlVirtualMachineGroupsInner sqlVirtualMachineGroups() { + return this.sqlVirtualMachineGroups; + } + + /** + * The SqlVirtualMachinesInner object to access its operations. + */ + private SqlVirtualMachinesInner sqlVirtualMachines; + + /** + * Gets the SqlVirtualMachinesInner object to access its operations. + * @return the SqlVirtualMachinesInner object. + */ + public SqlVirtualMachinesInner sqlVirtualMachines() { + return this.sqlVirtualMachines; + } + + /** + * Initializes an instance of SqlVirtualMachineManagementClient client. + * + * @param credentials the management credentials for Azure + */ + public SqlVirtualMachineManagementClientImpl(ServiceClientCredentials credentials) { + this("https://management.azure.com", credentials); + } + + /** + * Initializes an instance of SqlVirtualMachineManagementClient client. + * + * @param baseUrl the base URL of the host + * @param credentials the management credentials for Azure + */ + public SqlVirtualMachineManagementClientImpl(String baseUrl, ServiceClientCredentials credentials) { + super(baseUrl, credentials); + initialize(); + } + + /** + * Initializes an instance of SqlVirtualMachineManagementClient client. + * + * @param restClient the REST client to connect to Azure. + */ + public SqlVirtualMachineManagementClientImpl(RestClient restClient) { + super(restClient); + initialize(); + } + + protected void initialize() { + this.apiVersion = "2017-03-01-preview"; + this.acceptLanguage = "en-US"; + this.longRunningOperationRetryTimeout = 30; + this.generateClientRequestId = true; + this.availabilityGroupListeners = new AvailabilityGroupListenersInner(restClient().retrofit(), this); + this.operations = new OperationsInner(restClient().retrofit(), this); + this.sqlVirtualMachineGroups = new SqlVirtualMachineGroupsInner(restClient().retrofit(), this); + this.sqlVirtualMachines = new SqlVirtualMachinesInner(restClient().retrofit(), this); + this.azureClient = new AzureClient(this); + } + + /** + * Gets the User-Agent header for the client. + * + * @return the user agent string. + */ + @Override + public String userAgent() { + return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "SqlVirtualMachineManagementClient", "2017-03-01-preview"); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineManager.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineManager.java new file mode 100644 index 0000000000000..3acb87b6ac5e9 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachineManager.java @@ -0,0 +1,135 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.AzureResponseBuilder; +import com.microsoft.azure.credentials.AzureTokenCredentials; +import com.microsoft.azure.management.apigeneration.Beta; +import com.microsoft.azure.management.apigeneration.Beta.SinceVersion; +import com.microsoft.azure.arm.resources.AzureConfigurable; +import com.microsoft.azure.serializer.AzureJacksonAdapter; +import com.microsoft.rest.RestClient; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.AvailabilityGroupListeners; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.Operations; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineGroups; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines; +import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl; +import com.microsoft.azure.arm.resources.implementation.ManagerCore; + +/** + * Entry point to Azure SqlVirtualMachine resource management. + */ +public final class SqlVirtualMachineManager extends ManagerCore { + private AvailabilityGroupListeners availabilityGroupListeners; + private Operations operations; + private SqlVirtualMachineGroups sqlVirtualMachineGroups; + private SqlVirtualMachines sqlVirtualMachines; + /** + * Get a Configurable instance that can be used to create SqlVirtualMachineManager with optional configuration. + * + * @return the instance allowing configurations + */ + public static Configurable configure() { + return new SqlVirtualMachineManager.ConfigurableImpl(); + } + /** + * Creates an instance of SqlVirtualMachineManager that exposes SqlVirtualMachine resource management API entry points. + * + * @param credentials the credentials to use + * @param subscriptionId the subscription UUID + * @return the SqlVirtualMachineManager + */ + public static SqlVirtualMachineManager authenticate(AzureTokenCredentials credentials, String subscriptionId) { + return new SqlVirtualMachineManager(new RestClient.Builder() + .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) + .withCredentials(credentials) + .withSerializerAdapter(new AzureJacksonAdapter()) + .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) + .build(), subscriptionId); + } + /** + * Creates an instance of SqlVirtualMachineManager that exposes SqlVirtualMachine resource management API entry points. + * + * @param restClient the RestClient to be used for API calls. + * @param subscriptionId the subscription UUID + * @return the SqlVirtualMachineManager + */ + public static SqlVirtualMachineManager authenticate(RestClient restClient, String subscriptionId) { + return new SqlVirtualMachineManager(restClient, subscriptionId); + } + /** + * The interface allowing configurations to be set. + */ + public interface Configurable extends AzureConfigurable { + /** + * Creates an instance of SqlVirtualMachineManager that exposes SqlVirtualMachine management API entry points. + * + * @param credentials the credentials to use + * @param subscriptionId the subscription UUID + * @return the interface exposing SqlVirtualMachine management API entry points that work across subscriptions + */ + SqlVirtualMachineManager authenticate(AzureTokenCredentials credentials, String subscriptionId); + } + + /** + * @return Entry point to manage AvailabilityGroupListeners. + */ + public AvailabilityGroupListeners availabilityGroupListeners() { + if (this.availabilityGroupListeners == null) { + this.availabilityGroupListeners = new AvailabilityGroupListenersImpl(this); + } + return this.availabilityGroupListeners; + } + + /** + * @return Entry point to manage Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(this); + } + return this.operations; + } + + /** + * @return Entry point to manage SqlVirtualMachineGroups. + */ + public SqlVirtualMachineGroups sqlVirtualMachineGroups() { + if (this.sqlVirtualMachineGroups == null) { + this.sqlVirtualMachineGroups = new SqlVirtualMachineGroupsImpl(this); + } + return this.sqlVirtualMachineGroups; + } + + /** + * @return Entry point to manage SqlVirtualMachines. + */ + public SqlVirtualMachines sqlVirtualMachines() { + if (this.sqlVirtualMachines == null) { + this.sqlVirtualMachines = new SqlVirtualMachinesImpl(this); + } + return this.sqlVirtualMachines; + } + + /** + * The implementation for Configurable interface. + */ + private static final class ConfigurableImpl extends AzureConfigurableCoreImpl implements Configurable { + public SqlVirtualMachineManager authenticate(AzureTokenCredentials credentials, String subscriptionId) { + return SqlVirtualMachineManager.authenticate(buildRestClient(credentials), subscriptionId); + } + } + private SqlVirtualMachineManager(RestClient restClient, String subscriptionId) { + super( + restClient, + subscriptionId, + new SqlVirtualMachineManagementClientImpl(restClient).withSubscriptionId(subscriptionId)); + } +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachinesImpl.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachinesImpl.java new file mode 100644 index 0000000000000..626f62da62535 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachinesImpl.java @@ -0,0 +1,138 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * def + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.arm.resources.collection.implementation.GroupableResourcesCoreImpl; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachine; +import rx.Observable; +import rx.Completable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import com.microsoft.azure.arm.resources.ResourceUtilsCore; +import com.microsoft.azure.arm.utils.RXMapper; +import rx.functions.Func1; +import com.microsoft.azure.PagedList; +import com.microsoft.azure.Page; + +class SqlVirtualMachinesImpl extends GroupableResourcesCoreImpl implements SqlVirtualMachines { + protected SqlVirtualMachinesImpl(SqlVirtualMachineManager manager) { + super(manager.inner().sqlVirtualMachines(), manager); + } + + @Override + protected Observable getInnerAsync(String resourceGroupName, String name) { + SqlVirtualMachinesInner client = this.inner(); + return client.getByResourceGroupAsync(resourceGroupName, name); + } + + @Override + protected Completable deleteInnerAsync(String resourceGroupName, String name) { + SqlVirtualMachinesInner client = this.inner(); + return client.deleteAsync(resourceGroupName, name).toCompletable(); + } + + @Override + public Observable deleteByIdsAsync(Collection ids) { + if (ids == null || ids.isEmpty()) { + return Observable.empty(); + } + Collection> observables = new ArrayList<>(); + for (String id : ids) { + final String resourceGroupName = ResourceUtilsCore.groupFromResourceId(id); + final String name = ResourceUtilsCore.nameFromResourceId(id); + Observable o = RXMapper.map(this.inner().deleteAsync(resourceGroupName, name), id); + observables.add(o); + } + return Observable.mergeDelayError(observables); + } + + @Override + public Observable deleteByIdsAsync(String...ids) { + return this.deleteByIdsAsync(new ArrayList(Arrays.asList(ids))); + } + + @Override + public void deleteByIds(Collection ids) { + if (ids != null && !ids.isEmpty()) { + this.deleteByIdsAsync(ids).toBlocking().last(); + } + } + + @Override + public void deleteByIds(String...ids) { + this.deleteByIds(new ArrayList(Arrays.asList(ids))); + } + + @Override + public PagedList listByResourceGroup(String resourceGroupName) { + SqlVirtualMachinesInner client = this.inner(); + return this.wrapList(client.listByResourceGroup(resourceGroupName)); + } + + @Override + public Observable listByResourceGroupAsync(String resourceGroupName) { + SqlVirtualMachinesInner client = this.inner(); + return client.listByResourceGroupAsync(resourceGroupName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public SqlVirtualMachine call(SqlVirtualMachineInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public PagedList list() { + SqlVirtualMachinesInner client = this.inner(); + return this.wrapList(client.list()); + } + + @Override + public Observable listAsync() { + SqlVirtualMachinesInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public SqlVirtualMachine call(SqlVirtualMachineInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public SqlVirtualMachineImpl define(String name) { + return wrapModel(name); + } + + @Override + protected SqlVirtualMachineImpl wrapModel(SqlVirtualMachineInner inner) { + return new SqlVirtualMachineImpl(inner.name(), inner, manager()); + } + + @Override + protected SqlVirtualMachineImpl wrapModel(String name) { + return new SqlVirtualMachineImpl(name, new SqlVirtualMachineInner(), this.manager()); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachinesInner.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachinesInner.java new file mode 100644 index 0000000000000..3cac074ce5941 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/SqlVirtualMachinesInner.java @@ -0,0 +1,1379 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; + +import com.microsoft.azure.arm.collection.InnerSupportsGet; +import com.microsoft.azure.arm.collection.InnerSupportsDelete; +import com.microsoft.azure.arm.collection.InnerSupportsListing; +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachineUpdate; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in SqlVirtualMachines. + */ +public class SqlVirtualMachinesInner implements InnerSupportsGet, InnerSupportsDelete, InnerSupportsListing { + /** The Retrofit service to perform REST calls. */ + private SqlVirtualMachinesService service; + /** The service client containing this operation class. */ + private SqlVirtualMachineManagementClientImpl client; + + /** + * Initializes an instance of SqlVirtualMachinesInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public SqlVirtualMachinesInner(Retrofit retrofit, SqlVirtualMachineManagementClientImpl client) { + this.service = retrofit.create(SqlVirtualMachinesService.class); + this.client = client; + } + + /** + * The interface defining all the services for SqlVirtualMachines to be + * used by Retrofit to perform actually REST calls. + */ + interface SqlVirtualMachinesService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines list" }) + @GET("subscriptions/{subscriptionId}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines") + Observable> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines getByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}") + Observable> getByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineName") String sqlVirtualMachineName, @Path("subscriptionId") String subscriptionId, @Query("$expand") String expand, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines createOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}") + Observable> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineName") String sqlVirtualMachineName, @Path("subscriptionId") String subscriptionId, @Body SqlVirtualMachineInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines beginCreateOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}") + Observable> beginCreateOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineName") String sqlVirtualMachineName, @Path("subscriptionId") String subscriptionId, @Body SqlVirtualMachineInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines delete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineName") String sqlVirtualMachineName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines beginDelete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineName") String sqlVirtualMachineName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines update" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}") + Observable> update(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineName") String sqlVirtualMachineName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SqlVirtualMachineUpdate parameters, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines beginUpdate" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}") + Observable> beginUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("sqlVirtualMachineName") String sqlVirtualMachineName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SqlVirtualMachineUpdate parameters, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines listByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines") + Observable> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.SqlVirtualMachines listByResourceGroupNext" }) + @GET + Observable> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SqlVirtualMachineInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SqlVirtualMachineInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineInner object if successful. + */ + public SqlVirtualMachineInner getByResourceGroup(String resourceGroupName, String sqlVirtualMachineName) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).toBlocking().single().body(); + } + + /** + * Gets a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getByResourceGroupAsync(String resourceGroupName, String sqlVirtualMachineName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName), serviceCallback); + } + + /** + * Gets a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable getByResourceGroupAsync(String resourceGroupName, String sqlVirtualMachineName) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).map(new Func1, SqlVirtualMachineInner>() { + @Override + public SqlVirtualMachineInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String expand = null; + return service.getByResourceGroup(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), expand, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getByResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param expand The child resources to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineInner object if successful. + */ + public SqlVirtualMachineInner getByResourceGroup(String resourceGroupName, String sqlVirtualMachineName, String expand) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, expand).toBlocking().single().body(); + } + + /** + * Gets a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param expand The child resources to include in the response. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getByResourceGroupAsync(String resourceGroupName, String sqlVirtualMachineName, String expand, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, expand), serviceCallback); + } + + /** + * Gets a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param expand The child resources to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable getByResourceGroupAsync(String resourceGroupName, String sqlVirtualMachineName, String expand) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, expand).map(new Func1, SqlVirtualMachineInner>() { + @Override + public SqlVirtualMachineInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param expand The child resources to include in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName, String expand) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.getByResourceGroup(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), expand, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getByResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getByResourceGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Creates or updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param parameters The SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineInner object if successful. + */ + public SqlVirtualMachineInner createOrUpdate(String resourceGroupName, String sqlVirtualMachineName, SqlVirtualMachineInner parameters) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, parameters).toBlocking().last().body(); + } + + /** + * Creates or updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param parameters The SQL virtual machine. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineName, SqlVirtualMachineInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, parameters), serviceCallback); + } + + /** + * Creates or updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param parameters The SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineName, SqlVirtualMachineInner parameters) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, parameters).map(new Func1, SqlVirtualMachineInner>() { + @Override + public SqlVirtualMachineInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param parameters The SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName, SqlVirtualMachineInner parameters) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(parameters); + Observable> observable = service.createOrUpdate(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Creates or updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param parameters The SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineInner object if successful. + */ + public SqlVirtualMachineInner beginCreateOrUpdate(String resourceGroupName, String sqlVirtualMachineName, SqlVirtualMachineInner parameters) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, parameters).toBlocking().single().body(); + } + + /** + * Creates or updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param parameters The SQL virtual machine. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineName, SqlVirtualMachineInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, parameters), serviceCallback); + } + + /** + * Creates or updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param parameters The SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable beginCreateOrUpdateAsync(String resourceGroupName, String sqlVirtualMachineName, SqlVirtualMachineInner parameters) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, parameters).map(new Func1, SqlVirtualMachineInner>() { + @Override + public SqlVirtualMachineInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param parameters The SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName, SqlVirtualMachineInner parameters) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(parameters); + return service.beginCreateOrUpdate(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateOrUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateOrUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Deletes a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String resourceGroupName, String sqlVirtualMachineName) { + deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).toBlocking().last().body(); + } + + /** + * Deletes a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String resourceGroupName, String sqlVirtualMachineName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName), serviceCallback); + } + + /** + * Deletes a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String resourceGroupName, String sqlVirtualMachineName) { + return deleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Deletes a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String resourceGroupName, String sqlVirtualMachineName) { + beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).toBlocking().single().body(); + } + + /** + * Deletes a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String resourceGroupName, String sqlVirtualMachineName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName), serviceCallback); + } + + /** + * Deletes a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String resourceGroupName, String sqlVirtualMachineName) { + return beginDeleteWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineInner object if successful. + */ + public SqlVirtualMachineInner update(String resourceGroupName, String sqlVirtualMachineName) { + return updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).toBlocking().last().body(); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String sqlVirtualMachineName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName), serviceCallback); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String resourceGroupName, String sqlVirtualMachineName) { + return updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).map(new Func1, SqlVirtualMachineInner>() { + @Override + public SqlVirtualMachineInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final Map tags = null; + SqlVirtualMachineUpdate parameters = new SqlVirtualMachineUpdate(); + parameters.withTags(null); + Observable> observable = service.update(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineInner object if successful. + */ + public SqlVirtualMachineInner update(String resourceGroupName, String sqlVirtualMachineName, Map tags) { + return updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, tags).toBlocking().last().body(); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param tags Resource tags. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String sqlVirtualMachineName, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, tags), serviceCallback); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String resourceGroupName, String sqlVirtualMachineName, Map tags) { + return updateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, tags).map(new Func1, SqlVirtualMachineInner>() { + @Override + public SqlVirtualMachineInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName, Map tags) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(tags); + SqlVirtualMachineUpdate parameters = new SqlVirtualMachineUpdate(); + parameters.withTags(tags); + Observable> observable = service.update(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineInner object if successful. + */ + public SqlVirtualMachineInner beginUpdate(String resourceGroupName, String sqlVirtualMachineName) { + return beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).toBlocking().single().body(); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String resourceGroupName, String sqlVirtualMachineName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName), serviceCallback); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable beginUpdateAsync(String resourceGroupName, String sqlVirtualMachineName) { + return beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName).map(new Func1, SqlVirtualMachineInner>() { + @Override + public SqlVirtualMachineInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final Map tags = null; + SqlVirtualMachineUpdate parameters = new SqlVirtualMachineUpdate(); + parameters.withTags(null); + return service.beginUpdate(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SqlVirtualMachineInner object if successful. + */ + public SqlVirtualMachineInner beginUpdate(String resourceGroupName, String sqlVirtualMachineName, Map tags) { + return beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, tags).toBlocking().single().body(); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param tags Resource tags. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String resourceGroupName, String sqlVirtualMachineName, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, tags), serviceCallback); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable beginUpdateAsync(String resourceGroupName, String sqlVirtualMachineName, Map tags) { + return beginUpdateWithServiceResponseAsync(resourceGroupName, sqlVirtualMachineName, tags).map(new Func1, SqlVirtualMachineInner>() { + @Override + public SqlVirtualMachineInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates a SQL virtual machine. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param sqlVirtualMachineName Name of the SQL virtual machine. + * @param tags Resource tags. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SqlVirtualMachineInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String resourceGroupName, String sqlVirtualMachineName, Map tags) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (sqlVirtualMachineName == null) { + throw new IllegalArgumentException("Parameter sqlVirtualMachineName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(tags); + SqlVirtualMachineUpdate parameters = new SqlVirtualMachineUpdate(); + parameters.withTags(tags); + return service.beginUpdate(resourceGroupName, sqlVirtualMachineName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all SQL virtual machines in a resource group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SqlVirtualMachineInner> object if successful. + */ + public PagedList listByResourceGroup(final String resourceGroupName) { + ServiceResponse> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all SQL virtual machines in a resource group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupSinglePageAsync(resourceGroupName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all SQL virtual machines in a resource group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineInner> object + */ + public Observable> listByResourceGroupAsync(final String resourceGroupName) { + return listByResourceGroupWithServiceResponseAsync(resourceGroupName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all SQL virtual machines in a resource group. + * + * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineInner> object + */ + public Observable>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) { + return listByResourceGroupSinglePageAsync(resourceGroupName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all SQL virtual machines in a resource group. + * + ServiceResponse> * @param resourceGroupName Name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SqlVirtualMachineInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupSinglePageAsync(final String resourceGroupName) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SqlVirtualMachineInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all SQL virtual machines in a subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all SQL virtual machines in a subscription. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SqlVirtualMachineInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all SQL virtual machines in a resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<SqlVirtualMachineInner> object if successful. + */ + public PagedList listByResourceGroupNext(final String nextPageLink) { + ServiceResponse> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all SQL virtual machines in a resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all SQL virtual machines in a resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineInner> object + */ + public Observable> listByResourceGroupNextAsync(final String nextPageLink) { + return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all SQL virtual machines in a resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SqlVirtualMachineInner> object + */ + public Observable>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all SQL virtual machines in a resource group. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SqlVirtualMachineInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/package-info.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/package-info.java new file mode 100644 index 0000000000000..ce603ddbbe0c9 --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/implementation/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the implementation classes for SqlVirtualMachineManagementClient. + * The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener. + */ +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview.implementation; diff --git a/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/package-info.java b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/package-info.java new file mode 100644 index 0000000000000..4ab74de7b64eb --- /dev/null +++ b/sqlvirtualmachine/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sqlvirtualmachine/v2017_03_01_preview/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the classes for SqlVirtualMachineManagementClient. + * The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener. + */ +package com.microsoft.azure.management.sqlvirtualmachine.v2017_03_01_preview; From e467fe18c11c33fa368b3c5cd635d49757a66ecc Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Tue, 2 Jul 2019 21:05:07 -0700 Subject: [PATCH 074/147] Update version of appconfig to 1.0.0-preview.1 (#4237) * Update version of appconfig to 1.0.0-preview.1 * Update report versions for app configuration. --- appconfiguration/client/pom.xml | 6 +++--- eng/jacoco-test-coverage/pom.xml | 2 +- eng/spotbugs-aggregate-report/pom.xml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/appconfiguration/client/pom.xml b/appconfiguration/client/pom.xml index 3b3ca521e268a..65f9d1292bb72 100644 --- a/appconfiguration/client/pom.xml +++ b/appconfiguration/client/pom.xml @@ -13,7 +13,7 @@ com.azure azure-data-appconfiguration - 1.0.0-SNAPSHOT + 1.0.0-preview.1 Microsoft Azure client library for Application Configuration This package contains the Microsoft Azure Application Configuration client library. @@ -36,7 +36,7 @@ com.azure azure-core - 1.0.0-preview.1 + 1.0.0-preview.2 org.slf4j @@ -46,7 +46,7 @@ com.azure azure-core-test - 1.0.0-preview.1 + 1.0.0-preview.2 test diff --git a/eng/jacoco-test-coverage/pom.xml b/eng/jacoco-test-coverage/pom.xml index 0af2cfee8b3f9..b2eb87fb50723 100644 --- a/eng/jacoco-test-coverage/pom.xml +++ b/eng/jacoco-test-coverage/pom.xml @@ -59,7 +59,7 @@ com.azure azure-data-appconfiguration - ${version} + 1.0.0-preview.1 com.azure diff --git a/eng/spotbugs-aggregate-report/pom.xml b/eng/spotbugs-aggregate-report/pom.xml index 1b6da34c6bf24..d22d0d5a6722f 100644 --- a/eng/spotbugs-aggregate-report/pom.xml +++ b/eng/spotbugs-aggregate-report/pom.xml @@ -19,7 +19,7 @@ 1.2.0 2.0.0 10.5.0 - 1.0.0-SNAPSHOT + 1.0.0-preview.1 5.0.0-preview.1 From 1894a18da5169f371a1735afcb14636a59874cfd Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Tue, 2 Jul 2019 22:26:19 -0700 Subject: [PATCH 075/147] Add CHANGELOG known issues and features. (#4244) * Add changelog known issues and features. * Adding changed section. * Update changed/added section. --- eventhubs/client/CHANGELOG.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/eventhubs/client/CHANGELOG.md b/eventhubs/client/CHANGELOG.md index 677dfc353e3e7..331c6ad6b4477 100644 --- a/eventhubs/client/CHANGELOG.md +++ b/eventhubs/client/CHANGELOG.md @@ -1,4 +1,28 @@ # Release History ## 5.0.0-preview.1 (2019-07-01) -For release notes and more information please visit https://aka.ms/azure-sdk-preview1-java \ No newline at end of file +Version 5.0.0-preview.1 is a preview of our efforts in creating a client library that is developer-friendly, idiomatic +to the Java ecosystem, and as consistent across different languages and platforms as possible. The principles that guide +our efforts can be found in the [Azure SDK Design Guidelines for +.Java](https://azuresdkspecs.z5.web.core.windows.net/JavaSpec.html). + +For release notes and more information please visit https://aka.ms/azure-sdk-preview1-java + +### Features + +- Reactive streams support using [Project Reactor](https://projectreactor.io/). +- Fetch Event Hub and partition metadata using `EventHubClient`. +- Publish messages to an Azure Event Hub using `EventHubPublisher`. +- Receive messages from an Azure Event Hub using `EventHubConsumer`. + +### Known issues + +- AMQP protocol using web sockets is not implemented. +- Proxy support is not implemented. +- Event Host Processor is not implemented. +- Creating an `EventDataBatch` is not exposed. +- Getting `ReceiverRuntimeInformation` from `EventHubConsumer` is not implemented. +- `EventHubClient` does not clean up its `EventHubPublishers` and `EventHubConsumers`. These need to be closed manually + by calling `EventHubPublisher.close()` or `EventHubConsumer.close()`. +- Creating more than two concurrent `EventHubClients` or `EventHubConsumers` does not work. Limit usage of concurrent + clients and consumers to two to avoid failures. \ No newline at end of file From 7bfc13a1b218a64d7ec3cfe878c65977738f7c8f Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Wed, 3 Jul 2019 07:17:49 -0700 Subject: [PATCH 076/147] Update EventHub core dependency version to preview 2 (#4221) --- eventhubs/client/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/eventhubs/client/pom.xml b/eventhubs/client/pom.xml index bc86a93bfeb5e..80805194e0a77 100644 --- a/eventhubs/client/pom.xml +++ b/eventhubs/client/pom.xml @@ -38,12 +38,12 @@ com.azure azure-core - 1.0.0-preview.1 + 1.0.0-preview.2 com.azure azure-core-amqp - 1.0.0-preview.1 + 1.0.0-preview.2 com.microsoft.azure @@ -57,7 +57,7 @@ com.azure azure-core-test - 1.0.0-preview.1 + 1.0.0-preview.2 test From 44bb43daada48332af547acd5aa439329f029a93 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 08:41:05 -0700 Subject: [PATCH 077/147] Policy: updated azure-arm-client-runtime test jar dependency, pom structure (#4230) * updated azure-arm-client-runtime test jar dependency, pom structure * Update pom.xml --- policy/resource-manager/v2018_05_01/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/policy/resource-manager/v2018_05_01/pom.xml b/policy/resource-manager/v2018_05_01/pom.xml index 19d701cb0b806..d483a98022dfe 100644 --- a/policy/resource-manager/v2018_05_01/pom.xml +++ b/policy/resource-manager/v2018_05_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 5cfe04085381bfb296503ee9448cabe5abd87356 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 08:43:44 -0700 Subject: [PATCH 078/147] Recoveryservices (#4129) * generated v2016_08_10 of recoveryservicesbackup * generated v2018_01_10 of recoveryservices.siterecovery * update azure-arm-client-runtime test jar dependency * update azure-arm-client-runtime test jar dependency --- api-specs.json | 4 + .../resource-manager/v2016_08_10/pom.xml | 135 + .../v2016_08_10/ClientDiscoveryDisplay.java | 121 + .../ClientDiscoveryForLogSpecification.java | 95 + .../ClientDiscoveryForProperties.java | 43 + ...lientDiscoveryForServiceSpecification.java | 44 + .../ClientDiscoveryValueForSingleApi.java | 40 + .../backup/v2016_08_10/Operations.java | 27 + .../ClientDiscoveryValueForSingleApiImpl.java | 48 + ...ClientDiscoveryValueForSingleApiInner.java | 125 + .../implementation/IdParsingUtils.java | 57 + .../implementation/OperationsImpl.java | 49 + .../implementation/OperationsInner.java | 283 + .../v2016_08_10/implementation/PageImpl.java | 75 + .../RecoveryServicesBackupClientImpl.java | 173 + .../RecoveryServicesManager.java | 96 + .../implementation/package-info.java | 11 + .../backup/v2016_08_10/package-info.java | 11 + .../resource-manager/v2018_01_10/pom.xml | 135 + .../A2AApplyRecoveryPointInput.java | 20 + .../A2AContainerCreationInput.java | 20 + .../v2018_01_10/A2AContainerMappingInput.java | 74 + .../v2018_01_10/A2AEnableProtectionInput.java | 282 + .../v2018_01_10/A2AEventDetails.java | 177 + .../v2018_01_10/A2AFailoverProviderInput.java | 74 + .../v2018_01_10/A2APolicyCreationInput.java | 128 + .../v2018_01_10/A2APolicyDetails.java | 152 + .../v2018_01_10/A2AProtectedDiskDetails.java | 513 ++ .../A2AProtectedManagedDiskDetails.java | 567 ++ .../A2AProtectionContainerMappingDetails.java | 126 + .../v2018_01_10/A2ARecoveryPointDetails.java | 49 + .../v2018_01_10/A2AReplicationDetails.java | 837 +++ .../v2018_01_10/A2AReprotectInput.java | 178 + .../v2018_01_10/A2ARpRecoveryPointType.java | 47 + .../v2018_01_10/A2ASwitchProtectionInput.java | 256 + .../A2AUpdateContainerMappingInput.java | 74 + ...2AUpdateReplicationProtectedItemInput.java | 152 + .../v2018_01_10/A2AVmDiskInputDetails.java | 95 + .../A2AVmManagedDiskInputDetails.java | 149 + .../A2AVmManagedDiskUpdateDetails.java | 95 + .../siterecovery/v2018_01_10/ASRTask.java | 335 ++ .../AddRecoveryServicesProviderInput.java | 43 + ...coveryServicesProviderInputProperties.java | 95 + .../v2018_01_10/AddVCenterRequest.java | 43 + .../AddVCenterRequestProperties.java | 147 + .../v2018_01_10/AgentAutoUpdateStatus.java | 41 + .../v2018_01_10/AgentVersionStatus.java | 50 + .../siterecovery/v2018_01_10/Alert.java | 121 + .../v2018_01_10/AlertProperties.java | 96 + .../AlternateLocationRecoveryOption.java | 41 + .../v2018_01_10/ApplyRecoveryPointInput.java | 43 + .../ApplyRecoveryPointInputProperties.java | 69 + ...plyRecoveryPointProviderSpecificInput.java | 26 + .../v2018_01_10/AsrJobDetails.java | 20 + .../AutomationRunbookTaskDetails.java | 255 + .../v2018_01_10/AzureFabricCreationInput.java | 47 + .../AzureFabricSpecificDetails.java | 74 + ...AzureToAzureCreateNetworkMappingInput.java | 48 + .../AzureToAzureNetworkMappingSettings.java | 73 + ...AzureToAzureUpdateNetworkMappingInput.java | 47 + .../AzureToAzureVmSyncedConfigDetails.java | 97 + .../v2018_01_10/AzureVmDiskDetails.java | 199 + .../v2018_01_10/ComputeSizeErrorDetails.java | 70 + .../v2018_01_10/ConfigurationSettings.java | 27 + .../v2018_01_10/ConfigureAlertRequest.java | 43 + .../ConfigureAlertRequestProperties.java | 96 + .../ConsistencyCheckTaskDetails.java | 49 + .../CreateNetworkMappingInput.java | 43 + .../CreateNetworkMappingInputProperties.java | 95 + .../v2018_01_10/CreatePolicyInput.java | 43 + .../CreatePolicyInputProperties.java | 43 + .../CreateProtectionContainerInput.java | 43 + ...ateProtectionContainerInputProperties.java | 44 + ...CreateProtectionContainerMappingInput.java | 43 + ...ectionContainerMappingInputProperties.java | 95 + .../v2018_01_10/CreateRecoveryPlanInput.java | 43 + .../CreateRecoveryPlanInputProperties.java | 123 + .../v2018_01_10/CurrentJobDetails.java | 96 + .../v2018_01_10/CurrentScenarioDetails.java | 96 + .../siterecovery/v2018_01_10/DataStore.java | 147 + .../v2018_01_10/DataSyncStatus.java | 41 + .../v2018_01_10/DisableProtectionInput.java | 43 + .../DisableProtectionInputProperties.java | 71 + ...isableProtectionProviderSpecificInput.java | 24 + .../v2018_01_10/DisableProtectionReason.java | 41 + .../DiscoverProtectableItemRequest.java | 43 + ...coverProtectableItemRequestProperties.java | 95 + .../v2018_01_10/DiskAccountType.java | 44 + .../siterecovery/v2018_01_10/DiskDetails.java | 121 + .../v2018_01_10/DiskEncryptionInfo.java | 69 + .../v2018_01_10/DiskEncryptionKeyInfo.java | 69 + .../siterecovery/v2018_01_10/DiskType.java | 44 + .../v2018_01_10/DiskVolumeDetails.java | 69 + .../siterecovery/v2018_01_10/Display.java | 144 + .../v2018_01_10/EnableMigrationInput.java | 43 + .../EnableMigrationInputProperties.java | 69 + .../EnableMigrationProviderSpecificInput.java | 24 + .../v2018_01_10/EnableProtectionInput.java | 43 + .../EnableProtectionInputProperties.java | 98 + ...EnableProtectionProviderSpecificInput.java | 28 + .../v2018_01_10/EncryptionDetails.java | 96 + .../v2018_01_10/EthernetAddressType.java | 41 + .../siterecovery/v2018_01_10/Event.java | 47 + .../v2018_01_10/EventProperties.java | 282 + .../EventProviderSpecificDetails.java | 29 + .../v2018_01_10/EventQueryParameter.java | 202 + .../v2018_01_10/EventSpecificDetails.java | 24 + .../v2018_01_10/ExportJobDetails.java | 73 + .../siterecovery/v2018_01_10/Fabric.java | 120 + .../v2018_01_10/FabricCreationInput.java | 43 + .../FabricCreationInputProperties.java | 43 + .../v2018_01_10/FabricProperties.java | 226 + .../FabricReplicationGroupTaskDetails.java | 99 + ...bricSpecificCreateNetworkMappingInput.java | 26 + .../FabricSpecificCreationInput.java | 25 + .../v2018_01_10/FabricSpecificDetails.java | 28 + ...bricSpecificUpdateNetworkMappingInput.java | 26 + .../v2018_01_10/FailoverDeploymentModel.java | 44 + .../v2018_01_10/FailoverJobDetails.java | 48 + .../FailoverProcessServerRequest.java | 43 + ...ailoverProcessServerRequestProperties.java | 148 + ...iloverReplicationProtectedItemDetails.java | 252 + .../v2018_01_10/GroupTaskDetails.java | 55 + .../siterecovery/v2018_01_10/HealthError.java | 362 ++ .../v2018_01_10/HealthErrorCategory.java | 56 + .../v2018_01_10/HealthErrorSummary.java | 206 + .../HyperVReplica2012EventDetails.java | 125 + .../HyperVReplica2012R2EventDetails.java | 125 + ...rVReplicaAzureApplyRecoveryPointInput.java | 99 + ...perVReplicaAzureEnableProtectionInput.java | 389 ++ .../HyperVReplicaAzureEventDetails.java | 99 + ...perVReplicaAzureFailbackProviderInput.java | 99 + ...perVReplicaAzureFailoverProviderInput.java | 126 + .../HyperVReplicaAzurePolicyDetails.java | 181 + .../HyperVReplicaAzurePolicyInput.java | 156 + .../HyperVReplicaAzureReplicationDetails.java | 651 ++ .../HyperVReplicaAzureReprotectInput.java | 177 + ...HyperVReplicaAzureRpRecoveryPointType.java | 44 + ...reUpdateReplicationProtectedItemInput.java | 99 + .../HyperVReplicaBaseEventDetails.java | 125 + .../HyperVReplicaBasePolicyDetails.java | 282 + .../HyperVReplicaBaseReplicationDetails.java | 205 + .../HyperVReplicaBluePolicyDetails.java | 308 + .../HyperVReplicaBluePolicyInput.java | 307 + .../HyperVReplicaBlueReplicationDetails.java | 205 + .../HyperVReplicaPolicyDetails.java | 282 + .../v2018_01_10/HyperVReplicaPolicyInput.java | 281 + .../HyperVReplicaReplicationDetails.java | 205 + .../v2018_01_10/HyperVSiteDetails.java | 20 + .../HyperVVirtualMachineDetails.java | 210 + .../v2018_01_10/IdentityProviderDetails.java | 155 + .../v2018_01_10/IdentityProviderInput.java | 155 + .../v2018_01_10/InMageAgentDetails.java | 122 + .../InMageAgentVersionDetails.java | 124 + .../InMageAzureV2ApplyRecoveryPointInput.java | 47 + .../InMageAzureV2EnableProtectionInput.java | 415 ++ .../InMageAzureV2EventDetails.java | 204 + .../InMageAzureV2FailoverProviderInput.java | 74 + .../InMageAzureV2PolicyDetails.java | 152 + .../v2018_01_10/InMageAzureV2PolicyInput.java | 154 + .../InMageAzureV2ProtectedDiskDetails.java | 408 ++ .../InMageAzureV2RecoveryPointDetails.java | 47 + .../InMageAzureV2ReplicationDetails.java | 1307 +++++ .../InMageAzureV2ReprotectInput.java | 204 + ...V2UpdateReplicationProtectedItemInput.java | 99 + .../v2018_01_10/InMageBasePolicyDetails.java | 126 + ...isableProtectionProviderSpecificInput.java | 48 + .../v2018_01_10/InMageDiskDetails.java | 174 + .../v2018_01_10/InMageDiskExclusionInput.java | 71 + .../InMageDiskSignatureExclusionOptions.java | 44 + .../InMageEnableProtectionInput.java | 282 + .../InMageFailoverProviderInput.java | 77 + .../v2018_01_10/InMagePolicyDetails.java | 126 + .../v2018_01_10/InMagePolicyInput.java | 128 + .../InMageProtectedDiskDetails.java | 408 ++ .../v2018_01_10/InMageReplicationDetails.java | 992 ++++ .../v2018_01_10/InMageReprotectInput.java | 230 + .../InMageV2RpRecoveryPointType.java | 47 + .../InMageVolumeExclusionOptions.java | 74 + .../v2018_01_10/InconsistentVmDetails.java | 124 + .../InitialReplicationDetails.java | 69 + .../InlineWorkflowTaskDetails.java | 48 + .../v2018_01_10/InnerHealthError.java | 335 ++ .../v2018_01_10/InputEndpoint.java | 121 + .../siterecovery/v2018_01_10/Job.java | 47 + .../siterecovery/v2018_01_10/JobDetails.java | 57 + .../siterecovery/v2018_01_10/JobEntity.java | 174 + .../v2018_01_10/JobErrorDetails.java | 148 + .../v2018_01_10/JobProperties.java | 387 ++ .../v2018_01_10/JobQueryParameter.java | 147 + .../v2018_01_10/JobStatusEventDetails.java | 125 + .../v2018_01_10/JobTaskDetails.java | 48 + .../v2018_01_10/KeyEncryptionKeyInfo.java | 69 + .../siterecovery/v2018_01_10/LicenseType.java | 44 + .../v2018_01_10/LogicalNetwork.java | 47 + .../v2018_01_10/LogicalNetworkProperties.java | 123 + .../v2018_01_10/ManualActionTaskDetails.java | 99 + .../v2018_01_10/MasterTargetServer.java | 487 ++ .../v2018_01_10/MigrateInput.java | 43 + .../v2018_01_10/MigrateInputProperties.java | 43 + .../MigrateProviderSpecificInput.java | 24 + .../v2018_01_10/MigrationItem.java | 122 + .../v2018_01_10/MigrationItemOperation.java | 47 + .../v2018_01_10/MigrationItemProperties.java | 231 + .../MigrationItemsQueryParameter.java | 69 + .../MigrationProviderSpecificSettings.java | 24 + .../v2018_01_10/MigrationRecoveryPoint.java | 47 + .../MigrationRecoveryPointProperties.java | 49 + .../MigrationRecoveryPointType.java | 44 + .../v2018_01_10/MigrationRecoveryPoints.java | 42 + .../v2018_01_10/MigrationState.java | 68 + .../v2018_01_10/MobilityServiceUpdate.java | 95 + .../v2018_01_10/MultiVmGroupCreateOption.java | 41 + .../v2018_01_10/MultiVmSyncPointOption.java | 41 + .../v2018_01_10/MultiVmSyncStatus.java | 41 + .../siterecovery/v2018_01_10/Network.java | 47 + .../v2018_01_10/NetworkMapping.java | 122 + .../NetworkMappingFabricSpecificSettings.java | 26 + .../v2018_01_10/NetworkMappingProperties.java | 251 + .../v2018_01_10/NetworkProperties.java | 122 + .../siterecovery/v2018_01_10/OSDetails.java | 173 + .../v2018_01_10/OSDiskDetails.java | 95 + .../siterecovery/v2018_01_10/Operations.java | 19 + .../v2018_01_10/OperationsDiscovery.java | 40 + .../v2018_01_10/PlannedFailoverInput.java | 43 + .../PlannedFailoverInputProperties.java | 69 + .../siterecovery/v2018_01_10/Policy.java | 120 + .../v2018_01_10/PolicyProperties.java | 69 + .../PolicyProviderSpecificDetails.java | 33 + .../PolicyProviderSpecificInput.java | 30 + .../PossibleOperationsDirections.java | 41 + .../v2018_01_10/PresenceStatus.java | 44 + .../v2018_01_10/ProcessServer.java | 749 +++ .../v2018_01_10/ProtectableItem.java | 47 + .../ProtectableItemProperties.java | 200 + .../ProtectableItemQueryParameter.java | 43 + .../ProtectedItemsQueryParameter.java | 148 + .../v2018_01_10/ProtectionContainer.java | 122 + ...tectionContainerFabricSpecificDetails.java | 32 + .../ProtectionContainerMapping.java | 122 + .../ProtectionContainerMappingProperties.java | 304 + ...ntainerMappingProviderSpecificDetails.java | 25 + .../ProtectionContainerProperties.java | 199 + .../v2018_01_10/ProviderError.java | 147 + .../ProviderSpecificFailoverInput.java | 28 + .../ProviderSpecificRecoveryPointDetails.java | 25 + .../RcmAzureMigrationPolicyDetails.java | 153 + .../v2018_01_10/RecoveryPlan.java | 121 + .../RecoveryPlanA2AFailoverInput.java | 103 + .../v2018_01_10/RecoveryPlanAction.java | 122 + .../RecoveryPlanActionDetails.java | 26 + .../RecoveryPlanActionLocation.java | 41 + ...eryPlanAutomationRunbookActionDetails.java | 99 + .../v2018_01_10/RecoveryPlanGroup.java | 122 + .../RecoveryPlanGroupTaskDetails.java | 99 + .../v2018_01_10/RecoveryPlanGroupType.java | 44 + ...ryPlanHyperVReplicaAzureFailbackInput.java | 75 + ...ryPlanHyperVReplicaAzureFailoverInput.java | 126 + ...ecoveryPlanInMageAzureV2FailoverInput.java | 102 + .../RecoveryPlanInMageFailoverInput.java | 48 + .../RecoveryPlanManualActionDetails.java | 47 + .../RecoveryPlanPlannedFailoverInput.java | 43 + ...eryPlanPlannedFailoverInputProperties.java | 71 + .../v2018_01_10/RecoveryPlanProperties.java | 409 ++ .../RecoveryPlanProtectedItem.java | 69 + ...veryPlanProviderSpecificFailoverInput.java | 28 + .../RecoveryPlanScriptActionDetails.java | 99 + .../RecoveryPlanShutdownGroupTaskDetails.java | 99 + .../RecoveryPlanTestFailoverCleanupInput.java | 43 + ...lanTestFailoverCleanupInputProperties.java | 43 + .../RecoveryPlanTestFailoverInput.java | 43 + ...coveryPlanTestFailoverInputProperties.java | 149 + .../RecoveryPlanUnplannedFailoverInput.java | 43 + ...yPlanUnplannedFailoverInputProperties.java | 98 + .../v2018_01_10/RecoveryPoint.java | 47 + .../v2018_01_10/RecoveryPointProperties.java | 96 + .../v2018_01_10/RecoveryPointSyncType.java | 41 + .../v2018_01_10/RecoveryPointType.java | 44 + .../v2018_01_10/RecoveryPoints.java | 44 + .../v2018_01_10/RecoveryServicesProvider.java | 121 + .../RecoveryServicesProviderProperties.java | 435 ++ ...RemoveProtectionContainerMappingInput.java | 43 + ...ectionContainerMappingInputProperties.java | 43 + .../v2018_01_10/RenewCertificateInput.java | 43 + .../RenewCertificateInputProperties.java | 43 + .../v2018_01_10/ReplicationAlertSettings.java | 39 + .../v2018_01_10/ReplicationEvents.java | 38 + .../v2018_01_10/ReplicationFabrics.java | 100 + .../v2018_01_10/ReplicationGroupDetails.java | 20 + .../v2018_01_10/ReplicationJobs.java | 78 + .../ReplicationLogicalNetworks.java | 40 + .../ReplicationMigrationItems.java | 102 + .../ReplicationNetworkMappings.java | 65 + .../v2018_01_10/ReplicationNetworks.java | 49 + .../v2018_01_10/ReplicationPolicies.java | 50 + .../ReplicationProtectableItems.java | 42 + .../v2018_01_10/ReplicationProtectedItem.java | 123 + .../ReplicationProtectedItemOperation.java | 74 + .../ReplicationProtectedItemProperties.java | 724 +++ .../ReplicationProtectedItems.java | 186 + ...eplicationProtectionContainerMappings.java | 77 + .../ReplicationProtectionContainers.java | 84 + ...cationProviderContainerUnmappingInput.java | 43 + ...roviderSpecificContainerCreationInput.java | 25 + ...ProviderSpecificContainerMappingInput.java | 25 + .../ReplicationProviderSpecificSettings.java | 30 + ...erSpecificUpdateContainerMappingInput.java | 24 + .../v2018_01_10/ReplicationRecoveryPlans.java | 114 + .../ReplicationRecoveryServicesProviders.java | 84 + ...licationStorageClassificationMappings.java | 65 + .../ReplicationStorageClassifications.java | 49 + .../v2018_01_10/ReplicationVaultHealths.java | 36 + .../v2018_01_10/ReplicationvCenters.java | 62 + .../v2018_01_10/ResourceHealthSummary.java | 72 + .../v2018_01_10/ResumeJobParams.java | 43 + .../ResumeJobParamsProperties.java | 43 + .../v2018_01_10/RetentionVolume.java | 121 + .../v2018_01_10/ReverseReplicationInput.java | 43 + .../ReverseReplicationInputProperties.java | 69 + ...verseReplicationProviderSpecificInput.java | 27 + .../v2018_01_10/RoleAssignment.java | 147 + .../RpInMageRecoveryPointType.java | 44 + .../v2018_01_10/RunAsAccount.java | 69 + .../v2018_01_10/SanEnableProtectionInput.java | 20 + .../v2018_01_10/ScriptActionTaskDetails.java | 125 + .../v2018_01_10/ServiceError.java | 147 + .../v2018_01_10/SetMultiVmSyncStatus.java | 41 + .../siterecovery/v2018_01_10/Severity.java | 47 + .../v2018_01_10/SourceSiteOperations.java | 41 + .../v2018_01_10/StorageClassification.java | 47 + .../StorageClassificationMapping.java | 122 + .../StorageClassificationMappingInput.java | 43 + ...torageClassificationMappingProperties.java | 43 + .../StorageClassificationProperties.java | 43 + .../StorageMappingInputProperties.java | 43 + .../siterecovery/v2018_01_10/Subnet.java | 96 + .../v2018_01_10/SwitchProtectionInput.java | 43 + .../SwitchProtectionInputProperties.java | 69 + .../SwitchProtectionJobDetails.java | 47 + ...SwitchProtectionProviderSpecificInput.java | 24 + .../v2018_01_10/TargetComputeSize.java | 40 + .../TargetComputeSizeProperties.java | 227 + .../v2018_01_10/TargetComputeSizes.java | 31 + .../v2018_01_10/TaskTypeDetails.java | 31 + .../v2018_01_10/TestFailoverCleanupInput.java | 43 + .../TestFailoverCleanupInputProperties.java | 43 + .../v2018_01_10/TestFailoverInput.java | 43 + .../TestFailoverInputProperties.java | 147 + .../v2018_01_10/TestFailoverJobDetails.java | 178 + .../v2018_01_10/TestMigrateCleanupInput.java | 43 + .../TestMigrateCleanupInputProperties.java | 43 + .../v2018_01_10/TestMigrateInput.java | 43 + .../TestMigrateInputProperties.java | 43 + .../TestMigrateProviderSpecificInput.java | 24 + .../v2018_01_10/TestMigrationState.java | 50 + .../v2018_01_10/UnplannedFailoverInput.java | 43 + .../UnplannedFailoverInputProperties.java | 95 + .../v2018_01_10/UpdateMigrationItemInput.java | 43 + .../UpdateMigrationItemInputProperties.java | 43 + ...ateMigrationItemProviderSpecificInput.java | 24 + .../UpdateMobilityServiceRequest.java | 43 + ...pdateMobilityServiceRequestProperties.java | 43 + .../UpdateNetworkMappingInput.java | 43 + .../UpdateNetworkMappingInputProperties.java | 95 + .../v2018_01_10/UpdatePolicyInput.java | 43 + .../UpdatePolicyInputProperties.java | 43 + ...UpdateProtectionContainerMappingInput.java | 43 + ...ectionContainerMappingInputProperties.java | 43 + .../v2018_01_10/UpdateRecoveryPlanInput.java | 43 + .../UpdateRecoveryPlanInputProperties.java | 44 + .../UpdateReplicationProtectedItemInput.java | 43 + ...plicationProtectedItemInputProperties.java | 255 + ...ReplicationProtectedItemProviderInput.java | 26 + .../v2018_01_10/UpdateVCenterRequest.java | 43 + .../UpdateVCenterRequestProperties.java | 147 + .../siterecovery/v2018_01_10/VCenter.java | 121 + .../v2018_01_10/VCenterProperties.java | 305 + .../v2018_01_10/VMNicDetails.java | 355 ++ .../v2018_01_10/VMNicInputDetails.java | 147 + .../VMwareCbtContainerCreationInput.java | 20 + .../VMwareCbtContainerMappingInput.java | 177 + .../v2018_01_10/VMwareCbtDiskInput.java | 148 + .../VMwareCbtEnableMigrationInput.java | 335 ++ .../v2018_01_10/VMwareCbtMigrateInput.java | 47 + .../VMwareCbtMigrationDetails.java | 362 ++ .../v2018_01_10/VMwareCbtNicDetails.java | 209 + .../v2018_01_10/VMwareCbtNicInput.java | 147 + .../VMwareCbtPolicyCreationInput.java | 100 + .../VMwareCbtProtectedDiskDetails.java | 179 + ...eCbtProtectionContainerMappingDetails.java | 111 + .../VMwareCbtTestMigrateInput.java | 73 + .../VMwareCbtUpdateMigrationItemInput.java | 231 + .../v2018_01_10/VMwareDetails.java | 855 +++ .../VMwareV2FabricCreationInput.java | 73 + .../VMwareV2FabricSpecificDetails.java | 66 + .../VMwareVirtualMachineDetails.java | 284 + .../v2018_01_10/VaultHealthDetails.java | 45 + .../v2018_01_10/VaultHealthProperties.java | 122 + .../v2018_01_10/VersionDetails.java | 98 + .../VirtualMachineTaskDetails.java | 99 + .../v2018_01_10/VmNicUpdatesTaskDetails.java | 99 + .../siterecovery/v2018_01_10/VmmDetails.java | 20 + .../VmmToAzureCreateNetworkMappingInput.java | 21 + .../VmmToAzureNetworkMappingSettings.java | 20 + .../VmmToAzureUpdateNetworkMappingInput.java | 20 + .../VmmToVmmCreateNetworkMappingInput.java | 21 + .../VmmToVmmNetworkMappingSettings.java | 20 + .../VmmToVmmUpdateNetworkMappingInput.java | 20 + .../v2018_01_10/VmmVirtualMachineDetails.java | 210 + .../v2018_01_10/VmwareCbtPolicyDetails.java | 100 + .../v2018_01_10/implementation/AlertImpl.java | 136 + .../implementation/AlertInner.java | 71 + .../v2018_01_10/implementation/EventImpl.java | 65 + .../implementation/EventInner.java | 71 + .../implementation/FabricImpl.java | 135 + .../implementation/FabricInner.java | 71 + .../implementation/IdParsingUtils.java | 57 + .../v2018_01_10/implementation/JobImpl.java | 65 + .../v2018_01_10/implementation/JobInner.java | 71 + .../implementation/LogicalNetworkImpl.java | 67 + .../implementation/LogicalNetworkInner.java | 71 + .../implementation/MigrationItemImpl.java | 144 + .../implementation/MigrationItemInner.java | 71 + .../MigrationRecoveryPointImpl.java | 71 + .../MigrationRecoveryPointInner.java | 71 + .../MigrationRecoveryPointsImpl.java | 65 + .../MigrationRecoveryPointsInner.java | 428 ++ .../implementation/NetworkImpl.java | 67 + .../implementation/NetworkInner.java | 71 + .../implementation/NetworkMappingImpl.java | 144 + .../implementation/NetworkMappingInner.java | 76 + .../OperationsDiscoveryImpl.java | 52 + .../OperationsDiscoveryInner.java | 142 + .../implementation/OperationsImpl.java | 68 + .../implementation/OperationsInner.java | 300 + .../v2018_01_10/implementation/PageImpl.java | 75 + .../implementation/PolicyImpl.java | 138 + .../implementation/PolicyInner.java | 71 + .../implementation/ProtectableItemImpl.java | 69 + .../implementation/ProtectableItemInner.java | 71 + .../ProtectionContainerImpl.java | 139 + .../ProtectionContainerInner.java | 71 + .../ProtectionContainerMappingImpl.java | 144 + .../ProtectionContainerMappingInner.java | 71 + .../implementation/RecoveryPlanImpl.java | 139 + .../implementation/RecoveryPlanInner.java | 71 + .../implementation/RecoveryPointImpl.java | 71 + .../implementation/RecoveryPointInner.java | 71 + .../implementation/RecoveryPointsImpl.java | 65 + .../implementation/RecoveryPointsInner.java | 442 ++ .../RecoveryServicesManager.java | 363 ++ .../RecoveryServicesProviderImpl.java | 138 + .../RecoveryServicesProviderInner.java | 71 + .../ReplicationAlertSettingsImpl.java | 74 + .../ReplicationAlertSettingsInner.java | 587 ++ .../implementation/ReplicationEventsImpl.java | 65 + .../ReplicationEventsInner.java | 514 ++ .../ReplicationFabricsImpl.java | 129 + .../ReplicationFabricsInner.java | 2111 +++++++ .../implementation/ReplicationJobsImpl.java | 114 + .../implementation/ReplicationJobsInner.java | 1375 +++++ .../ReplicationLogicalNetworksImpl.java | 65 + .../ReplicationLogicalNetworksInner.java | 412 ++ .../ReplicationMigrationItemsImpl.java | 138 + .../ReplicationMigrationItemsInner.java | 2445 ++++++++ .../ReplicationNetworkMappingsImpl.java | 99 + .../ReplicationNetworkMappingsInner.java | 1672 ++++++ .../ReplicationNetworksImpl.java | 83 + .../ReplicationNetworksInner.java | 654 +++ .../ReplicationPoliciesImpl.java | 81 + .../ReplicationPoliciesInner.java | 1260 ++++ .../ReplicationProtectableItemsImpl.java | 65 + .../ReplicationProtectableItemsInner.java | 560 ++ .../ReplicationProtectedItemImpl.java | 145 + .../ReplicationProtectedItemInner.java | 71 + .../ReplicationProtectedItemsImpl.java | 214 + .../ReplicationProtectedItemsInner.java | 5215 +++++++++++++++++ ...cationProtectionContainerMappingsImpl.java | 105 + ...ationProtectionContainerMappingsInner.java | 2070 +++++++ .../ReplicationProtectionContainersImpl.java | 123 + .../ReplicationProtectionContainersInner.java | 1960 +++++++ .../ReplicationRecoveryPlansImpl.java | 157 + .../ReplicationRecoveryPlansInner.java | 2216 +++++++ ...licationRecoveryServicesProvidersImpl.java | 117 + ...icationRecoveryServicesProvidersInner.java | 1414 +++++ ...tionStorageClassificationMappingsImpl.java | 99 + ...ionStorageClassificationMappingsInner.java | 1270 ++++ ...ReplicationStorageClassificationsImpl.java | 83 + ...eplicationStorageClassificationsInner.java | 654 +++ .../ReplicationVaultHealthsImpl.java | 54 + .../ReplicationVaultHealthsInner.java | 291 + .../ReplicationvCentersImpl.java | 99 + .../ReplicationvCentersInner.java | 1588 +++++ .../SiteRecoveryManagementClientImpl.java | 550 ++ .../StorageClassificationImpl.java | 67 + .../StorageClassificationInner.java | 71 + .../StorageClassificationMappingImpl.java | 141 + .../StorageClassificationMappingInner.java | 71 + .../implementation/TargetComputeSizeImpl.java | 51 + .../TargetComputeSizeInner.java | 122 + .../TargetComputeSizesImpl.java | 53 + .../TargetComputeSizesInner.java | 327 ++ .../implementation/VCenterImpl.java | 141 + .../implementation/VCenterInner.java | 71 + .../VaultHealthDetailsImpl.java | 52 + .../VaultHealthDetailsInner.java | 71 + .../implementation/package-info.java | 10 + .../v2018_01_10/package-info.java | 10 + 508 files changed, 83804 insertions(+) create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/pom.xml create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryDisplay.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForLogSpecification.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForProperties.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForServiceSpecification.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryValueForSingleApi.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/Operations.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/ClientDiscoveryValueForSingleApiImpl.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/ClientDiscoveryValueForSingleApiInner.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/IdParsingUtils.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/OperationsImpl.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/OperationsInner.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/PageImpl.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/RecoveryServicesBackupClientImpl.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/RecoveryServicesManager.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/package-info.java create mode 100644 recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/package-info.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/pom.xml create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AApplyRecoveryPointInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AContainerCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AContainerMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AEnableProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AEventDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AFailoverProviderInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2APolicyCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2APolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectedDiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectedManagedDiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectionContainerMappingDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ARecoveryPointDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AReplicationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AReprotectInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ARpRecoveryPointType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ASwitchProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AUpdateContainerMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AUpdateReplicationProtectedItemInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmDiskInputDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmManagedDiskInputDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmManagedDiskUpdateDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ASRTask.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddRecoveryServicesProviderInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddRecoveryServicesProviderInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddVCenterRequest.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddVCenterRequestProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AgentAutoUpdateStatus.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AgentVersionStatus.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Alert.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AlertProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AlternateLocationRecoveryOption.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AsrJobDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AutomationRunbookTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureFabricCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureFabricSpecificDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureCreateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureNetworkMappingSettings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureUpdateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureVmSyncedConfigDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureVmDiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ComputeSizeErrorDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigurationSettings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigureAlertRequest.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigureAlertRequestProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConsistencyCheckTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateNetworkMappingInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreatePolicyInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreatePolicyInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerMappingInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateRecoveryPlanInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateRecoveryPlanInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CurrentJobDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CurrentScenarioDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DataStore.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DataSyncStatus.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionReason.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiscoverProtectableItemRequest.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiscoverProtectableItemRequestProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskAccountType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskEncryptionInfo.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskEncryptionKeyInfo.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskVolumeDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Display.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EncryptionDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EthernetAddressType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Event.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventProviderSpecificDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventQueryParameter.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventSpecificDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ExportJobDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Fabric.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricCreationInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricReplicationGroupTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificCreateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificUpdateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverDeploymentModel.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverJobDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverProcessServerRequest.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverProcessServerRequestProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverReplicationProtectedItemDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/GroupTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthError.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthErrorCategory.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthErrorSummary.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplica2012EventDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplica2012R2EventDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureApplyRecoveryPointInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureEnableProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureEventDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureFailbackProviderInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureFailoverProviderInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzurePolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzurePolicyInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureReplicationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureReprotectInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureRpRecoveryPointType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureUpdateReplicationProtectedItemInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBaseEventDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBasePolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBaseReplicationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBluePolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBluePolicyInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBlueReplicationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaPolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaPolicyInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaReplicationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVSiteDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVVirtualMachineDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/IdentityProviderDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/IdentityProviderInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAgentDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAgentVersionDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ApplyRecoveryPointInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2EnableProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2EventDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2FailoverProviderInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2PolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2PolicyInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ProtectedDiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2RecoveryPointDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ReplicationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ReprotectInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2UpdateReplicationProtectedItemInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageBasePolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDisableProtectionProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskExclusionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskSignatureExclusionOptions.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageEnableProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageFailoverProviderInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMagePolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMagePolicyInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageProtectedDiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageReplicationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageReprotectInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageV2RpRecoveryPointType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageVolumeExclusionOptions.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InconsistentVmDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InitialReplicationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InlineWorkflowTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InnerHealthError.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InputEndpoint.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Job.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobEntity.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobErrorDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobQueryParameter.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobStatusEventDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/KeyEncryptionKeyInfo.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LicenseType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LogicalNetwork.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LogicalNetworkProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ManualActionTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MasterTargetServer.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItem.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemOperation.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemsQueryParameter.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationProviderSpecificSettings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPoint.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPointProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPointType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPoints.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationState.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MobilityServiceUpdate.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmGroupCreateOption.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmSyncPointOption.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmSyncStatus.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Network.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMapping.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMappingFabricSpecificSettings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMappingProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OSDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OSDiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Operations.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OperationsDiscovery.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PlannedFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PlannedFailoverInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Policy.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProviderSpecificDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PossibleOperationsDirections.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PresenceStatus.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProcessServer.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItem.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItemProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItemQueryParameter.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectedItemsQueryParameter.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainer.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerFabricSpecificDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMapping.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMappingProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMappingProviderSpecificDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderError.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderSpecificFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderSpecificRecoveryPointDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RcmAzureMigrationPolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlan.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanA2AFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanAction.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanActionDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanActionLocation.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanAutomationRunbookActionDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroup.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroupTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroupType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanHyperVReplicaAzureFailbackInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanHyperVReplicaAzureFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanInMageAzureV2FailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanInMageFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanManualActionDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanPlannedFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanPlannedFailoverInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProtectedItem.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProviderSpecificFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanScriptActionDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanShutdownGroupTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverCleanupInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverCleanupInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanUnplannedFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanUnplannedFailoverInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPoint.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointSyncType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPoints.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryServicesProvider.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryServicesProviderProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RemoveProtectionContainerMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RemoveProtectionContainerMappingInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RenewCertificateInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RenewCertificateInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationAlertSettings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationEvents.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationFabrics.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationGroupDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationJobs.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationLogicalNetworks.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationMigrationItems.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationNetworkMappings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationNetworks.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationPolicies.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectableItems.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItem.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItemOperation.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItemProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItems.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectionContainerMappings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectionContainers.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderContainerUnmappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificContainerCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificContainerMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificSettings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificUpdateContainerMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationRecoveryPlans.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationRecoveryServicesProviders.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationStorageClassificationMappings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationStorageClassifications.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationVaultHealths.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationvCenters.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResourceHealthSummary.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResumeJobParams.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResumeJobParamsProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RetentionVolume.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RoleAssignment.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RpInMageRecoveryPointType.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RunAsAccount.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SanEnableProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ScriptActionTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ServiceError.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SetMultiVmSyncStatus.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Severity.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SourceSiteOperations.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassification.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMapping.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMappingProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageMappingInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Subnet.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionJobDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSize.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSizeProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSizes.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TaskTypeDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverCleanupInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverCleanupInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverJobDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateCleanupInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateCleanupInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrationState.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UnplannedFailoverInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UnplannedFailoverInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemProviderSpecificInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMobilityServiceRequest.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMobilityServiceRequestProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateNetworkMappingInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdatePolicyInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdatePolicyInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateProtectionContainerMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateProtectionContainerMappingInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateRecoveryPlanInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateRecoveryPlanInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemInputProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemProviderInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateVCenterRequest.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateVCenterRequestProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VCenter.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VCenterProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMNicDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMNicInputDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtContainerCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtContainerMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtDiskInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtEnableMigrationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtMigrateInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtMigrationDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtNicDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtNicInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtPolicyCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtProtectedDiskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtProtectionContainerMappingDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtTestMigrateInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtUpdateMigrationItemInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareV2FabricCreationInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareV2FabricSpecificDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareVirtualMachineDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VaultHealthDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VaultHealthProperties.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VersionDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VirtualMachineTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmNicUpdatesTaskDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureCreateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureNetworkMappingSettings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureUpdateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmCreateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmNetworkMappingSettings.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmUpdateNetworkMappingInput.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmVirtualMachineDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmwareCbtPolicyDetails.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/AlertImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/AlertInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/EventImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/EventInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/FabricImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/FabricInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/IdParsingUtils.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/JobImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/JobInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/LogicalNetworkImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/LogicalNetworkInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationItemImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationItemInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkMappingImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkMappingInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsDiscoveryImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsDiscoveryInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PageImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PolicyImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PolicyInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectableItemImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectableItemInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerMappingImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerMappingInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPlanImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPlanInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesManager.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesProviderImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesProviderInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationAlertSettingsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationAlertSettingsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationEventsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationEventsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationFabricsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationFabricsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationJobsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationJobsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationLogicalNetworksImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationLogicalNetworksInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationMigrationItemsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationMigrationItemsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworkMappingsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworkMappingsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworksImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworksInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationPoliciesImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationPoliciesInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectableItemsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectableItemsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainerMappingsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainerMappingsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainersImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainersInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryPlansImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryPlansInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryServicesProvidersImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryServicesProvidersInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationMappingsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationMappingsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationVaultHealthsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationVaultHealthsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationvCentersImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationvCentersInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/SiteRecoveryManagementClientImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationMappingImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationMappingInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizeImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizeInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizesImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizesInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VCenterImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VCenterInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VaultHealthDetailsImpl.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VaultHealthDetailsInner.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/package-info.java create mode 100644 recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/package-info.java diff --git a/api-specs.json b/api-specs.json index 901c9b31536e8..059bfafbe5eba 100644 --- a/api-specs.json +++ b/api-specs.json @@ -206,6 +206,10 @@ "source": "specification/recoveryservicesbackup/resource-manager/readme.md", "args": "--multiapi --fluent" }, + "recoveryservicessiterecovery/resource-manager": { + "source": "specification/recoveryservicessiterecovery/resource-manager/readme.md", + "args": "--multiapi --fluent" + }, "redis/resource-manager": { "source": "specification/redis/resource-manager/readme.md", "args": "--multiapi --fluent", diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/pom.xml b/recoveryservices.backup/resource-manager/v2016_08_10/pom.xml new file mode 100644 index 0000000000000..27c7ec3c99c98 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + com.microsoft.azure.recoveryservices.backup.v2016_08_10 + + com.microsoft.azure + azure-arm-parent + 1.1.0 + ../../../pom.management.xml + + azure-mgmt-recoveryservices + 1.0.0-beta + jar + Microsoft Azure SDK for RecoveryServices Management + This package contains Microsoft RecoveryServices Management SDK. + https://github.com/Azure/azure-sdk-for-java + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + UTF-8 + + + + + microsoft + Microsoft + + + + + com.microsoft.azure + azure-client-runtime + + + com.microsoft.azure + azure-arm-client-runtime + + + junit + junit + test + + + com.microsoft.azure + azure-client-authentication + test + + + com.microsoft.azure + azure-mgmt-resources + test + + + com.microsoft.azure + azure-arm-client-runtime + test-jar + test + + 1.6.5 + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + true + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + com.microsoft.azure.management.apigeneration.LangDefinitionProcessor + + + true + true + + true + true + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.search + + + /** +
* Copyright (c) Microsoft Corporation. All rights reserved. +
* Licensed under the MIT License. See License.txt in the project root for +
* license information. +
*/ + ]]> +
+
+
+
+
+
diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryDisplay.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryDisplay.java new file mode 100644 index 0000000000000..04ce825d5954a --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryDisplay.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Localized display information of an operation. + */ +public class ClientDiscoveryDisplay { + /** + * Name of the provider for display purposes. + */ + @JsonProperty(value = "provider") + private String provider; + + /** + * ResourceType for which this Operation can be performed. + */ + @JsonProperty(value = "resource") + private String resource; + + /** + * Operations Name itself. + */ + @JsonProperty(value = "operation") + private String operation; + + /** + * Description of the operation having details of what operation is about. + */ + @JsonProperty(value = "description") + private String description; + + /** + * Get name of the provider for display purposes. + * + * @return the provider value + */ + public String provider() { + return this.provider; + } + + /** + * Set name of the provider for display purposes. + * + * @param provider the provider value to set + * @return the ClientDiscoveryDisplay object itself. + */ + public ClientDiscoveryDisplay withProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get resourceType for which this Operation can be performed. + * + * @return the resource value + */ + public String resource() { + return this.resource; + } + + /** + * Set resourceType for which this Operation can be performed. + * + * @param resource the resource value to set + * @return the ClientDiscoveryDisplay object itself. + */ + public ClientDiscoveryDisplay withResource(String resource) { + this.resource = resource; + return this; + } + + /** + * Get operations Name itself. + * + * @return the operation value + */ + public String operation() { + return this.operation; + } + + /** + * Set operations Name itself. + * + * @param operation the operation value to set + * @return the ClientDiscoveryDisplay object itself. + */ + public ClientDiscoveryDisplay withOperation(String operation) { + this.operation = operation; + return this; + } + + /** + * Get description of the operation having details of what operation is about. + * + * @return the description value + */ + public String description() { + return this.description; + } + + /** + * Set description of the operation having details of what operation is about. + * + * @param description the description value to set + * @return the ClientDiscoveryDisplay object itself. + */ + public ClientDiscoveryDisplay withDescription(String description) { + this.description = description; + return this; + } + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForLogSpecification.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForLogSpecification.java new file mode 100644 index 0000000000000..b10032623cd84 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForLogSpecification.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Class to represent shoebox log specification in json client discovery. + */ +public class ClientDiscoveryForLogSpecification { + /** + * Name for shoebox log specification. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Localized display name. + */ + @JsonProperty(value = "displayName") + private String displayName; + + /** + * blob duration of shoebox log specification. + */ + @JsonProperty(value = "blobDuration") + private String blobDuration; + + /** + * Get name for shoebox log specification. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set name for shoebox log specification. + * + * @param name the name value to set + * @return the ClientDiscoveryForLogSpecification object itself. + */ + public ClientDiscoveryForLogSpecification withName(String name) { + this.name = name; + return this; + } + + /** + * Get localized display name. + * + * @return the displayName value + */ + public String displayName() { + return this.displayName; + } + + /** + * Set localized display name. + * + * @param displayName the displayName value to set + * @return the ClientDiscoveryForLogSpecification object itself. + */ + public ClientDiscoveryForLogSpecification withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get blob duration of shoebox log specification. + * + * @return the blobDuration value + */ + public String blobDuration() { + return this.blobDuration; + } + + /** + * Set blob duration of shoebox log specification. + * + * @param blobDuration the blobDuration value to set + * @return the ClientDiscoveryForLogSpecification object itself. + */ + public ClientDiscoveryForLogSpecification withBlobDuration(String blobDuration) { + this.blobDuration = blobDuration; + return this; + } + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForProperties.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForProperties.java new file mode 100644 index 0000000000000..a60fd82f02db4 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Class to represent shoebox properties in json client discovery. + */ +public class ClientDiscoveryForProperties { + /** + * Operation properties. + */ + @JsonProperty(value = "serviceSpecification") + private ClientDiscoveryForServiceSpecification serviceSpecification; + + /** + * Get operation properties. + * + * @return the serviceSpecification value + */ + public ClientDiscoveryForServiceSpecification serviceSpecification() { + return this.serviceSpecification; + } + + /** + * Set operation properties. + * + * @param serviceSpecification the serviceSpecification value to set + * @return the ClientDiscoveryForProperties object itself. + */ + public ClientDiscoveryForProperties withServiceSpecification(ClientDiscoveryForServiceSpecification serviceSpecification) { + this.serviceSpecification = serviceSpecification; + return this; + } + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForServiceSpecification.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForServiceSpecification.java new file mode 100644 index 0000000000000..10751babda68c --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryForServiceSpecification.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Class to represent shoebox service specification in json client discovery. + */ +public class ClientDiscoveryForServiceSpecification { + /** + * List of log specifications of this operation. + */ + @JsonProperty(value = "logSpecifications") + private List logSpecifications; + + /** + * Get list of log specifications of this operation. + * + * @return the logSpecifications value + */ + public List logSpecifications() { + return this.logSpecifications; + } + + /** + * Set list of log specifications of this operation. + * + * @param logSpecifications the logSpecifications value to set + * @return the ClientDiscoveryForServiceSpecification object itself. + */ + public ClientDiscoveryForServiceSpecification withLogSpecifications(List logSpecifications) { + this.logSpecifications = logSpecifications; + return this; + } + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryValueForSingleApi.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryValueForSingleApi.java new file mode 100644 index 0000000000000..c26975aa6ee8b --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/ClientDiscoveryValueForSingleApi.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation.RecoveryServicesManager; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation.ClientDiscoveryValueForSingleApiInner; + +/** + * Type representing ClientDiscoveryValueForSingleApi. + */ +public interface ClientDiscoveryValueForSingleApi extends HasInner, HasManager { + /** + * @return the display value. + */ + ClientDiscoveryDisplay display(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the origin value. + */ + String origin(); + + /** + * @return the properties value. + */ + ClientDiscoveryForProperties properties(); + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/Operations.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/Operations.java new file mode 100644 index 0000000000000..5f99e0af292f6 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/Operations.java @@ -0,0 +1,27 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation.OperationsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Operations. + */ +public interface Operations extends HasInner { + /** + * Returns the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/ClientDiscoveryValueForSingleApiImpl.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/ClientDiscoveryValueForSingleApiImpl.java new file mode 100644 index 0000000000000..eb81b1001b768 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/ClientDiscoveryValueForSingleApiImpl.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; + +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.ClientDiscoveryValueForSingleApi; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.ClientDiscoveryDisplay; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.ClientDiscoveryForProperties; + +class ClientDiscoveryValueForSingleApiImpl extends WrapperImpl implements ClientDiscoveryValueForSingleApi { + private final RecoveryServicesManager manager; + ClientDiscoveryValueForSingleApiImpl(ClientDiscoveryValueForSingleApiInner inner, RecoveryServicesManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public ClientDiscoveryDisplay display() { + return this.inner().display(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String origin() { + return this.inner().origin(); + } + + @Override + public ClientDiscoveryForProperties properties() { + return this.inner().properties(); + } + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/ClientDiscoveryValueForSingleApiInner.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/ClientDiscoveryValueForSingleApiInner.java new file mode 100644 index 0000000000000..befce18db34e3 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/ClientDiscoveryValueForSingleApiInner.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; + +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.ClientDiscoveryDisplay; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.ClientDiscoveryForProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Available operation details. + */ +public class ClientDiscoveryValueForSingleApiInner { + /** + * Name of the Operation. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Contains the localized display information for this particular + * operation. + */ + @JsonProperty(value = "display") + private ClientDiscoveryDisplay display; + + /** + * The intended executor of the operation;governs the display of the + * operation in the RBAC UX and the audit logs UX. + */ + @JsonProperty(value = "origin") + private String origin; + + /** + * ShoeBox properties for the given operation. + */ + @JsonProperty(value = "properties") + private ClientDiscoveryForProperties properties; + + /** + * Get name of the Operation. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set name of the Operation. + * + * @param name the name value to set + * @return the ClientDiscoveryValueForSingleApiInner object itself. + */ + public ClientDiscoveryValueForSingleApiInner withName(String name) { + this.name = name; + return this; + } + + /** + * Get contains the localized display information for this particular operation. + * + * @return the display value + */ + public ClientDiscoveryDisplay display() { + return this.display; + } + + /** + * Set contains the localized display information for this particular operation. + * + * @param display the display value to set + * @return the ClientDiscoveryValueForSingleApiInner object itself. + */ + public ClientDiscoveryValueForSingleApiInner withDisplay(ClientDiscoveryDisplay display) { + this.display = display; + return this; + } + + /** + * Get the intended executor of the operation;governs the display of the operation in the RBAC UX and the audit logs UX. + * + * @return the origin value + */ + public String origin() { + return this.origin; + } + + /** + * Set the intended executor of the operation;governs the display of the operation in the RBAC UX and the audit logs UX. + * + * @param origin the origin value to set + * @return the ClientDiscoveryValueForSingleApiInner object itself. + */ + public ClientDiscoveryValueForSingleApiInner withOrigin(String origin) { + this.origin = origin; + return this; + } + + /** + * Get shoeBox properties for the given operation. + * + * @return the properties value + */ + public ClientDiscoveryForProperties properties() { + return this.properties; + } + + /** + * Set shoeBox properties for the given operation. + * + * @param properties the properties value to set + * @return the ClientDiscoveryValueForSingleApiInner object itself. + */ + public ClientDiscoveryValueForSingleApiInner withProperties(ClientDiscoveryForProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/IdParsingUtils.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/IdParsingUtils.java new file mode 100644 index 0000000000000..c66f66e65f716 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/IdParsingUtils.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; +import java.util.Arrays; +import java.util.Iterator; + +class IdParsingUtils { + public static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + public static String getValueFromIdByPosition(String id, int pos) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + int index = 0; + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (index == pos) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + index++; + } + return null; + } +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/OperationsImpl.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/OperationsImpl.java new file mode 100644 index 0000000000000..a6f7f3cc78af9 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/OperationsImpl.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.Operations; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.ClientDiscoveryValueForSingleApi; + +class OperationsImpl extends WrapperImpl implements Operations { + private final RecoveryServicesManager manager; + + OperationsImpl(RecoveryServicesManager manager) { + super(manager.inner().operations()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable listAsync() { + OperationsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public ClientDiscoveryValueForSingleApi call(ClientDiscoveryValueForSingleApiInner inner) { + return new ClientDiscoveryValueForSingleApiImpl(inner, manager()); + } + }); + } + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/OperationsInner.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/OperationsInner.java new file mode 100644 index 0000000000000..e27d87748ec3a --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/OperationsInner.java @@ -0,0 +1,283 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Operations. + */ +public class OperationsInner { + /** The Retrofit service to perform REST calls. */ + private OperationsService service; + /** The service client containing this operation class. */ + private RecoveryServicesBackupClientImpl client; + + /** + * Initializes an instance of OperationsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public OperationsInner(Retrofit retrofit, RecoveryServicesBackupClientImpl client) { + this.service = retrofit.create(OperationsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Operations to be + * used by Retrofit to perform actually REST calls. + */ + interface OperationsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.Operations list" }) + @GET("providers/Microsoft.RecoveryServices/operations") + Observable> list(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.Operations listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Returns the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ClientDiscoveryValueForSingleApiInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Returns the list of available operations. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Returns the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ClientDiscoveryValueForSingleApiInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Returns the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ClientDiscoveryValueForSingleApiInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Returns the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ClientDiscoveryValueForSingleApiInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Returns the list of available operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ClientDiscoveryValueForSingleApiInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Returns the list of available operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Returns the list of available operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ClientDiscoveryValueForSingleApiInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Returns the list of available operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ClientDiscoveryValueForSingleApiInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Returns the list of available operations. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ClientDiscoveryValueForSingleApiInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/PageImpl.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/PageImpl.java new file mode 100644 index 0000000000000..963a8fcb43780 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/PageImpl.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.Page; +import java.util.List; + +/** + * An instance of this class defines a page of Azure resources and a link to + * get the next page of resources, if any. + * + * @param type of Azure resource + */ +public class PageImpl implements Page { + /** + * The link to the next page. + */ + @JsonProperty("nextLink") + private String nextPageLink; + + /** + * The list of items. + */ + @JsonProperty("value") + private List items; + + /** + * Gets the link to the next page. + * + * @return the link to the next page. + */ + @Override + public String nextPageLink() { + return this.nextPageLink; + } + + /** + * Gets the list of items. + * + * @return the list of items in {@link List}. + */ + @Override + public List items() { + return items; + } + + /** + * Sets the link to the next page. + * + * @param nextPageLink the link to the next page. + * @return this Page object itself. + */ + public PageImpl setNextPageLink(String nextPageLink) { + this.nextPageLink = nextPageLink; + return this; + } + + /** + * Sets the list of items. + * + * @param items the list of items in {@link List}. + * @return this Page object itself. + */ + public PageImpl setItems(List items) { + this.items = items; + return this; + } +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/RecoveryServicesBackupClientImpl.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/RecoveryServicesBackupClientImpl.java new file mode 100644 index 0000000000000..5bc6ebefbe494 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/RecoveryServicesBackupClientImpl.java @@ -0,0 +1,173 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; + +import com.microsoft.azure.AzureClient; +import com.microsoft.azure.AzureServiceClient; +import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.microsoft.rest.RestClient; + +/** + * Initializes a new instance of the RecoveryServicesBackupClientImpl class. + */ +public class RecoveryServicesBackupClientImpl extends AzureServiceClient { + /** the {@link AzureClient} used for long running operations. */ + private AzureClient azureClient; + + /** + * Gets the {@link AzureClient} used for long running operations. + * @return the azure client; + */ + public AzureClient getAzureClient() { + return this.azureClient; + } + + /** Client Api Version. */ + private String apiVersion; + + /** + * Gets Client Api Version. + * + * @return the apiVersion value. + */ + public String apiVersion() { + return this.apiVersion; + } + + /** The preferred language for the response. */ + private String acceptLanguage; + + /** + * Gets The preferred language for the response. + * + * @return the acceptLanguage value. + */ + public String acceptLanguage() { + return this.acceptLanguage; + } + + /** + * Sets The preferred language for the response. + * + * @param acceptLanguage the acceptLanguage value. + * @return the service client itself + */ + public RecoveryServicesBackupClientImpl withAcceptLanguage(String acceptLanguage) { + this.acceptLanguage = acceptLanguage; + return this; + } + + /** The retry timeout in seconds for Long Running Operations. Default value is 30. */ + private int longRunningOperationRetryTimeout; + + /** + * Gets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @return the longRunningOperationRetryTimeout value. + */ + public int longRunningOperationRetryTimeout() { + return this.longRunningOperationRetryTimeout; + } + + /** + * Sets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. + * @return the service client itself + */ + public RecoveryServicesBackupClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { + this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; + return this; + } + + /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ + private boolean generateClientRequestId; + + /** + * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @return the generateClientRequestId value. + */ + public boolean generateClientRequestId() { + return this.generateClientRequestId; + } + + /** + * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @param generateClientRequestId the generateClientRequestId value. + * @return the service client itself + */ + public RecoveryServicesBackupClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { + this.generateClientRequestId = generateClientRequestId; + return this; + } + + /** + * The OperationsInner object to access its operations. + */ + private OperationsInner operations; + + /** + * Gets the OperationsInner object to access its operations. + * @return the OperationsInner object. + */ + public OperationsInner operations() { + return this.operations; + } + + /** + * Initializes an instance of RecoveryServicesBackupClient client. + * + * @param credentials the management credentials for Azure + */ + public RecoveryServicesBackupClientImpl(ServiceClientCredentials credentials) { + this("https://management.azure.com", credentials); + } + + /** + * Initializes an instance of RecoveryServicesBackupClient client. + * + * @param baseUrl the base URL of the host + * @param credentials the management credentials for Azure + */ + public RecoveryServicesBackupClientImpl(String baseUrl, ServiceClientCredentials credentials) { + super(baseUrl, credentials); + initialize(); + } + + /** + * Initializes an instance of RecoveryServicesBackupClient client. + * + * @param restClient the REST client to connect to Azure. + */ + public RecoveryServicesBackupClientImpl(RestClient restClient) { + super(restClient); + initialize(); + } + + protected void initialize() { + this.apiVersion = "2016-08-10"; + this.acceptLanguage = "en-US"; + this.longRunningOperationRetryTimeout = 30; + this.generateClientRequestId = true; + this.operations = new OperationsInner(restClient().retrofit(), this); + this.azureClient = new AzureClient(this); + } + + /** + * Gets the User-Agent header for the client. + * + * @return the user agent string. + */ + @Override + public String userAgent() { + return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "RecoveryServicesBackupClient", "2016-08-10"); + } +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/RecoveryServicesManager.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/RecoveryServicesManager.java new file mode 100644 index 0000000000000..83e5f5259ef6c --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/RecoveryServicesManager.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.AzureResponseBuilder; +import com.microsoft.azure.credentials.AzureTokenCredentials; +import com.microsoft.azure.management.apigeneration.Beta; +import com.microsoft.azure.management.apigeneration.Beta.SinceVersion; +import com.microsoft.azure.arm.resources.AzureConfigurable; +import com.microsoft.azure.serializer.AzureJacksonAdapter; +import com.microsoft.rest.RestClient; +import com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.Operations; +import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl; +import com.microsoft.azure.arm.resources.implementation.ManagerCore; + +/** + * Entry point to Azure RecoveryServices resource management. + */ +public final class RecoveryServicesManager extends ManagerCore { + private Operations operations; + /** + * Get a Configurable instance that can be used to create RecoveryServicesManager with optional configuration. + * + * @return the instance allowing configurations + */ + public static Configurable configure() { + return new RecoveryServicesManager.ConfigurableImpl(); + } + /** + * Creates an instance of RecoveryServicesManager that exposes RecoveryServices resource management API entry points. + * + * @param credentials the credentials to use + * @return the RecoveryServicesManager + */ + public static RecoveryServicesManager authenticate(AzureTokenCredentials credentials) { + return new RecoveryServicesManager(new RestClient.Builder() + .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) + .withCredentials(credentials) + .withSerializerAdapter(new AzureJacksonAdapter()) + .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) + .build()); + } + /** + * Creates an instance of RecoveryServicesManager that exposes RecoveryServices resource management API entry points. + * + * @param restClient the RestClient to be used for API calls. + * @return the RecoveryServicesManager + */ + public static RecoveryServicesManager authenticate(RestClient restClient) { + return new RecoveryServicesManager(restClient); + } + /** + * The interface allowing configurations to be set. + */ + public interface Configurable extends AzureConfigurable { + /** + * Creates an instance of RecoveryServicesManager that exposes RecoveryServices management API entry points. + * + * @param credentials the credentials to use + * @return the interface exposing RecoveryServices management API entry points that work across subscriptions + */ + RecoveryServicesManager authenticate(AzureTokenCredentials credentials); + } + + /** + * @return Entry point to manage Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(this); + } + return this.operations; + } + + /** + * The implementation for Configurable interface. + */ + private static final class ConfigurableImpl extends AzureConfigurableCoreImpl implements Configurable { + public RecoveryServicesManager authenticate(AzureTokenCredentials credentials) { + return RecoveryServicesManager.authenticate(buildRestClient(credentials)); + } + } + private RecoveryServicesManager(RestClient restClient) { + super( + restClient, + null, + new RecoveryServicesBackupClientImpl(restClient)); + } +} diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/package-info.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/package-info.java new file mode 100644 index 0000000000000..cb2c8c0a99b97 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/implementation/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the implementation classes for RecoveryServicesBackupClient. + * Open API 2.0 Specs for Azure RecoveryServices Backup service. + */ +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10.implementation; diff --git a/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/package-info.java b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/package-info.java new file mode 100644 index 0000000000000..77fe3324d6330 --- /dev/null +++ b/recoveryservices.backup/resource-manager/v2016_08_10/src/main/java/com/microsoft/azure/management/recoveryservices/backup/v2016_08_10/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the classes for RecoveryServicesBackupClient. + * Open API 2.0 Specs for Azure RecoveryServices Backup service. + */ +package com.microsoft.azure.management.recoveryservices.backup.v2016_08_10; diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/pom.xml b/recoveryservices.siterecovery/resource-manager/v2018_01_10/pom.xml new file mode 100644 index 0000000000000..561d37a745749 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + com.microsoft.azure.recoveryservices.siterecovery.v2018_01_10 + + com.microsoft.azure + azure-arm-parent + 1.1.0 + ../../../pom.management.xml + + azure-mgmt-recoveryservices + 1.0.0-beta + jar + Microsoft Azure SDK for RecoveryServices Management + This package contains Microsoft RecoveryServices Management SDK. + https://github.com/Azure/azure-sdk-for-java + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + UTF-8 + + + + + microsoft + Microsoft + + + + + com.microsoft.azure + azure-client-runtime + + + com.microsoft.azure + azure-arm-client-runtime + + + junit + junit + test + + + com.microsoft.azure + azure-client-authentication + test + + + com.microsoft.azure + azure-mgmt-resources + test + + + com.microsoft.azure + azure-arm-client-runtime + test-jar + test + + 1.6.5 + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + true + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + com.microsoft.azure.management.apigeneration.LangDefinitionProcessor + + + true + true + + true + true + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.search + + + /** +
* Copyright (c) Microsoft Corporation. All rights reserved. +
* Licensed under the MIT License. See License.txt in the project root for +
* license information. +
*/ + ]]> +
+
+
+
+
+
diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AApplyRecoveryPointInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AApplyRecoveryPointInput.java new file mode 100644 index 0000000000000..c09d2b7233625 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AApplyRecoveryPointInput.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * ApplyRecoveryPoint input specific to A2A provider. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AApplyRecoveryPointInput extends ApplyRecoveryPointProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AContainerCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AContainerCreationInput.java new file mode 100644 index 0000000000000..e131df958b69b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AContainerCreationInput.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A cloud creation input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AContainerCreationInput extends ReplicationProviderSpecificContainerCreationInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AContainerMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AContainerMappingInput.java new file mode 100644 index 0000000000000..5713ab5ae50d0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AContainerMappingInput.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A container mapping input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AContainerMappingInput extends ReplicationProviderSpecificContainerMappingInput { + /** + * A value indicating whether the auto update is enabled. Possible values + * include: 'Disabled', 'Enabled'. + */ + @JsonProperty(value = "agentAutoUpdateStatus") + private AgentAutoUpdateStatus agentAutoUpdateStatus; + + /** + * The automation account arm id. + */ + @JsonProperty(value = "automationAccountArmId") + private String automationAccountArmId; + + /** + * Get a value indicating whether the auto update is enabled. Possible values include: 'Disabled', 'Enabled'. + * + * @return the agentAutoUpdateStatus value + */ + public AgentAutoUpdateStatus agentAutoUpdateStatus() { + return this.agentAutoUpdateStatus; + } + + /** + * Set a value indicating whether the auto update is enabled. Possible values include: 'Disabled', 'Enabled'. + * + * @param agentAutoUpdateStatus the agentAutoUpdateStatus value to set + * @return the A2AContainerMappingInput object itself. + */ + public A2AContainerMappingInput withAgentAutoUpdateStatus(AgentAutoUpdateStatus agentAutoUpdateStatus) { + this.agentAutoUpdateStatus = agentAutoUpdateStatus; + return this; + } + + /** + * Get the automation account arm id. + * + * @return the automationAccountArmId value + */ + public String automationAccountArmId() { + return this.automationAccountArmId; + } + + /** + * Set the automation account arm id. + * + * @param automationAccountArmId the automationAccountArmId value to set + * @return the A2AContainerMappingInput object itself. + */ + public A2AContainerMappingInput withAutomationAccountArmId(String automationAccountArmId) { + this.automationAccountArmId = automationAccountArmId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AEnableProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AEnableProtectionInput.java new file mode 100644 index 0000000000000..07b9f8533af99 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AEnableProtectionInput.java @@ -0,0 +1,282 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A enable protection input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AEnableProtectionInput extends EnableProtectionProviderSpecificInput { + /** + * The fabric specific object Id of the virtual machine. + */ + @JsonProperty(value = "fabricObjectId") + private String fabricObjectId; + + /** + * The recovery container Id. + */ + @JsonProperty(value = "recoveryContainerId") + private String recoveryContainerId; + + /** + * The recovery resource group Id. Valid for V2 scenarios. + */ + @JsonProperty(value = "recoveryResourceGroupId") + private String recoveryResourceGroupId; + + /** + * The recovery cloud service Id. Valid for V1 scenarios. + */ + @JsonProperty(value = "recoveryCloudServiceId") + private String recoveryCloudServiceId; + + /** + * The recovery availability set Id. + */ + @JsonProperty(value = "recoveryAvailabilitySetId") + private String recoveryAvailabilitySetId; + + /** + * The list of vm disk details. + */ + @JsonProperty(value = "vmDisks") + private List vmDisks; + + /** + * The list of vm managed disk details. + */ + @JsonProperty(value = "vmManagedDisks") + private List vmManagedDisks; + + /** + * The multi vm group name. + */ + @JsonProperty(value = "multiVmGroupName") + private String multiVmGroupName; + + /** + * The boot diagnostic storage account. + */ + @JsonProperty(value = "recoveryBootDiagStorageAccountId") + private String recoveryBootDiagStorageAccountId; + + /** + * The recovery disk encryption information. + */ + @JsonProperty(value = "diskEncryptionInfo") + private DiskEncryptionInfo diskEncryptionInfo; + + /** + * Get the fabric specific object Id of the virtual machine. + * + * @return the fabricObjectId value + */ + public String fabricObjectId() { + return this.fabricObjectId; + } + + /** + * Set the fabric specific object Id of the virtual machine. + * + * @param fabricObjectId the fabricObjectId value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withFabricObjectId(String fabricObjectId) { + this.fabricObjectId = fabricObjectId; + return this; + } + + /** + * Get the recovery container Id. + * + * @return the recoveryContainerId value + */ + public String recoveryContainerId() { + return this.recoveryContainerId; + } + + /** + * Set the recovery container Id. + * + * @param recoveryContainerId the recoveryContainerId value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withRecoveryContainerId(String recoveryContainerId) { + this.recoveryContainerId = recoveryContainerId; + return this; + } + + /** + * Get the recovery resource group Id. Valid for V2 scenarios. + * + * @return the recoveryResourceGroupId value + */ + public String recoveryResourceGroupId() { + return this.recoveryResourceGroupId; + } + + /** + * Set the recovery resource group Id. Valid for V2 scenarios. + * + * @param recoveryResourceGroupId the recoveryResourceGroupId value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withRecoveryResourceGroupId(String recoveryResourceGroupId) { + this.recoveryResourceGroupId = recoveryResourceGroupId; + return this; + } + + /** + * Get the recovery cloud service Id. Valid for V1 scenarios. + * + * @return the recoveryCloudServiceId value + */ + public String recoveryCloudServiceId() { + return this.recoveryCloudServiceId; + } + + /** + * Set the recovery cloud service Id. Valid for V1 scenarios. + * + * @param recoveryCloudServiceId the recoveryCloudServiceId value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withRecoveryCloudServiceId(String recoveryCloudServiceId) { + this.recoveryCloudServiceId = recoveryCloudServiceId; + return this; + } + + /** + * Get the recovery availability set Id. + * + * @return the recoveryAvailabilitySetId value + */ + public String recoveryAvailabilitySetId() { + return this.recoveryAvailabilitySetId; + } + + /** + * Set the recovery availability set Id. + * + * @param recoveryAvailabilitySetId the recoveryAvailabilitySetId value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withRecoveryAvailabilitySetId(String recoveryAvailabilitySetId) { + this.recoveryAvailabilitySetId = recoveryAvailabilitySetId; + return this; + } + + /** + * Get the list of vm disk details. + * + * @return the vmDisks value + */ + public List vmDisks() { + return this.vmDisks; + } + + /** + * Set the list of vm disk details. + * + * @param vmDisks the vmDisks value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withVmDisks(List vmDisks) { + this.vmDisks = vmDisks; + return this; + } + + /** + * Get the list of vm managed disk details. + * + * @return the vmManagedDisks value + */ + public List vmManagedDisks() { + return this.vmManagedDisks; + } + + /** + * Set the list of vm managed disk details. + * + * @param vmManagedDisks the vmManagedDisks value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withVmManagedDisks(List vmManagedDisks) { + this.vmManagedDisks = vmManagedDisks; + return this; + } + + /** + * Get the multi vm group name. + * + * @return the multiVmGroupName value + */ + public String multiVmGroupName() { + return this.multiVmGroupName; + } + + /** + * Set the multi vm group name. + * + * @param multiVmGroupName the multiVmGroupName value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withMultiVmGroupName(String multiVmGroupName) { + this.multiVmGroupName = multiVmGroupName; + return this; + } + + /** + * Get the boot diagnostic storage account. + * + * @return the recoveryBootDiagStorageAccountId value + */ + public String recoveryBootDiagStorageAccountId() { + return this.recoveryBootDiagStorageAccountId; + } + + /** + * Set the boot diagnostic storage account. + * + * @param recoveryBootDiagStorageAccountId the recoveryBootDiagStorageAccountId value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withRecoveryBootDiagStorageAccountId(String recoveryBootDiagStorageAccountId) { + this.recoveryBootDiagStorageAccountId = recoveryBootDiagStorageAccountId; + return this; + } + + /** + * Get the recovery disk encryption information. + * + * @return the diskEncryptionInfo value + */ + public DiskEncryptionInfo diskEncryptionInfo() { + return this.diskEncryptionInfo; + } + + /** + * Set the recovery disk encryption information. + * + * @param diskEncryptionInfo the diskEncryptionInfo value to set + * @return the A2AEnableProtectionInput object itself. + */ + public A2AEnableProtectionInput withDiskEncryptionInfo(DiskEncryptionInfo diskEncryptionInfo) { + this.diskEncryptionInfo = diskEncryptionInfo; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AEventDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AEventDetails.java new file mode 100644 index 0000000000000..7a026a7d2112b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AEventDetails.java @@ -0,0 +1,177 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Model class for event details of a A2A event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AEventDetails extends EventProviderSpecificDetails { + /** + * The protected item arm name. + */ + @JsonProperty(value = "protectedItemName") + private String protectedItemName; + + /** + * The azure vm arm id. + */ + @JsonProperty(value = "fabricObjectId") + private String fabricObjectId; + + /** + * Fabric arm name. + */ + @JsonProperty(value = "fabricName") + private String fabricName; + + /** + * The fabric location. + */ + @JsonProperty(value = "fabricLocation") + private String fabricLocation; + + /** + * Remote fabric arm name. + */ + @JsonProperty(value = "remoteFabricName") + private String remoteFabricName; + + /** + * Remote fabric location. + */ + @JsonProperty(value = "remoteFabricLocation") + private String remoteFabricLocation; + + /** + * Get the protected item arm name. + * + * @return the protectedItemName value + */ + public String protectedItemName() { + return this.protectedItemName; + } + + /** + * Set the protected item arm name. + * + * @param protectedItemName the protectedItemName value to set + * @return the A2AEventDetails object itself. + */ + public A2AEventDetails withProtectedItemName(String protectedItemName) { + this.protectedItemName = protectedItemName; + return this; + } + + /** + * Get the azure vm arm id. + * + * @return the fabricObjectId value + */ + public String fabricObjectId() { + return this.fabricObjectId; + } + + /** + * Set the azure vm arm id. + * + * @param fabricObjectId the fabricObjectId value to set + * @return the A2AEventDetails object itself. + */ + public A2AEventDetails withFabricObjectId(String fabricObjectId) { + this.fabricObjectId = fabricObjectId; + return this; + } + + /** + * Get fabric arm name. + * + * @return the fabricName value + */ + public String fabricName() { + return this.fabricName; + } + + /** + * Set fabric arm name. + * + * @param fabricName the fabricName value to set + * @return the A2AEventDetails object itself. + */ + public A2AEventDetails withFabricName(String fabricName) { + this.fabricName = fabricName; + return this; + } + + /** + * Get the fabric location. + * + * @return the fabricLocation value + */ + public String fabricLocation() { + return this.fabricLocation; + } + + /** + * Set the fabric location. + * + * @param fabricLocation the fabricLocation value to set + * @return the A2AEventDetails object itself. + */ + public A2AEventDetails withFabricLocation(String fabricLocation) { + this.fabricLocation = fabricLocation; + return this; + } + + /** + * Get remote fabric arm name. + * + * @return the remoteFabricName value + */ + public String remoteFabricName() { + return this.remoteFabricName; + } + + /** + * Set remote fabric arm name. + * + * @param remoteFabricName the remoteFabricName value to set + * @return the A2AEventDetails object itself. + */ + public A2AEventDetails withRemoteFabricName(String remoteFabricName) { + this.remoteFabricName = remoteFabricName; + return this; + } + + /** + * Get remote fabric location. + * + * @return the remoteFabricLocation value + */ + public String remoteFabricLocation() { + return this.remoteFabricLocation; + } + + /** + * Set remote fabric location. + * + * @param remoteFabricLocation the remoteFabricLocation value to set + * @return the A2AEventDetails object itself. + */ + public A2AEventDetails withRemoteFabricLocation(String remoteFabricLocation) { + this.remoteFabricLocation = remoteFabricLocation; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AFailoverProviderInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AFailoverProviderInput.java new file mode 100644 index 0000000000000..67f5f8b8be98f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AFailoverProviderInput.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A provider specific input for failover. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AFailoverProviderInput extends ProviderSpecificFailoverInput { + /** + * The recovery point id to be passed to failover to a particular recovery + * point. In case of latest recovery point, null should be passed. + */ + @JsonProperty(value = "recoveryPointId") + private String recoveryPointId; + + /** + * A value indicating whether to use recovery cloud service for TFO or not. + */ + @JsonProperty(value = "cloudServiceCreationOption") + private String cloudServiceCreationOption; + + /** + * Get the recovery point id to be passed to failover to a particular recovery point. In case of latest recovery point, null should be passed. + * + * @return the recoveryPointId value + */ + public String recoveryPointId() { + return this.recoveryPointId; + } + + /** + * Set the recovery point id to be passed to failover to a particular recovery point. In case of latest recovery point, null should be passed. + * + * @param recoveryPointId the recoveryPointId value to set + * @return the A2AFailoverProviderInput object itself. + */ + public A2AFailoverProviderInput withRecoveryPointId(String recoveryPointId) { + this.recoveryPointId = recoveryPointId; + return this; + } + + /** + * Get a value indicating whether to use recovery cloud service for TFO or not. + * + * @return the cloudServiceCreationOption value + */ + public String cloudServiceCreationOption() { + return this.cloudServiceCreationOption; + } + + /** + * Set a value indicating whether to use recovery cloud service for TFO or not. + * + * @param cloudServiceCreationOption the cloudServiceCreationOption value to set + * @return the A2AFailoverProviderInput object itself. + */ + public A2AFailoverProviderInput withCloudServiceCreationOption(String cloudServiceCreationOption) { + this.cloudServiceCreationOption = cloudServiceCreationOption; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2APolicyCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2APolicyCreationInput.java new file mode 100644 index 0000000000000..5417ca549b8c6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2APolicyCreationInput.java @@ -0,0 +1,128 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A Policy creation input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2APolicyCreationInput extends PolicyProviderSpecificInput { + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistory") + private Integer recoveryPointHistory; + + /** + * The crash consistent snapshot frequency (in minutes). + */ + @JsonProperty(value = "crashConsistentFrequencyInMinutes") + private Integer crashConsistentFrequencyInMinutes; + + /** + * The app consistent snapshot frequency (in minutes). + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * A value indicating whether multi-VM sync has to be enabled. Value should + * be 'Enabled' or 'Disabled'. Possible values include: 'Enable', + * 'Disable'. + */ + @JsonProperty(value = "multiVmSyncStatus", required = true) + private SetMultiVmSyncStatus multiVmSyncStatus; + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistory value + */ + public Integer recoveryPointHistory() { + return this.recoveryPointHistory; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistory the recoveryPointHistory value to set + * @return the A2APolicyCreationInput object itself. + */ + public A2APolicyCreationInput withRecoveryPointHistory(Integer recoveryPointHistory) { + this.recoveryPointHistory = recoveryPointHistory; + return this; + } + + /** + * Get the crash consistent snapshot frequency (in minutes). + * + * @return the crashConsistentFrequencyInMinutes value + */ + public Integer crashConsistentFrequencyInMinutes() { + return this.crashConsistentFrequencyInMinutes; + } + + /** + * Set the crash consistent snapshot frequency (in minutes). + * + * @param crashConsistentFrequencyInMinutes the crashConsistentFrequencyInMinutes value to set + * @return the A2APolicyCreationInput object itself. + */ + public A2APolicyCreationInput withCrashConsistentFrequencyInMinutes(Integer crashConsistentFrequencyInMinutes) { + this.crashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes; + return this; + } + + /** + * Get the app consistent snapshot frequency (in minutes). + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency (in minutes). + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the A2APolicyCreationInput object itself. + */ + public A2APolicyCreationInput withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get a value indicating whether multi-VM sync has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values include: 'Enable', 'Disable'. + * + * @return the multiVmSyncStatus value + */ + public SetMultiVmSyncStatus multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi-VM sync has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values include: 'Enable', 'Disable'. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the A2APolicyCreationInput object itself. + */ + public A2APolicyCreationInput withMultiVmSyncStatus(SetMultiVmSyncStatus multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2APolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2APolicyDetails.java new file mode 100644 index 0000000000000..6ea4fc9b6f374 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2APolicyDetails.java @@ -0,0 +1,152 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A specific policy details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2APolicyDetails extends PolicyProviderSpecificDetails { + /** + * The recovery point threshold in minutes. + */ + @JsonProperty(value = "recoveryPointThresholdInMinutes") + private Integer recoveryPointThresholdInMinutes; + + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistory") + private Integer recoveryPointHistory; + + /** + * The app consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * A value indicating whether multi-VM sync has to be enabled. + */ + @JsonProperty(value = "multiVmSyncStatus") + private String multiVmSyncStatus; + + /** + * The crash consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "crashConsistentFrequencyInMinutes") + private Integer crashConsistentFrequencyInMinutes; + + /** + * Get the recovery point threshold in minutes. + * + * @return the recoveryPointThresholdInMinutes value + */ + public Integer recoveryPointThresholdInMinutes() { + return this.recoveryPointThresholdInMinutes; + } + + /** + * Set the recovery point threshold in minutes. + * + * @param recoveryPointThresholdInMinutes the recoveryPointThresholdInMinutes value to set + * @return the A2APolicyDetails object itself. + */ + public A2APolicyDetails withRecoveryPointThresholdInMinutes(Integer recoveryPointThresholdInMinutes) { + this.recoveryPointThresholdInMinutes = recoveryPointThresholdInMinutes; + return this; + } + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistory value + */ + public Integer recoveryPointHistory() { + return this.recoveryPointHistory; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistory the recoveryPointHistory value to set + * @return the A2APolicyDetails object itself. + */ + public A2APolicyDetails withRecoveryPointHistory(Integer recoveryPointHistory) { + this.recoveryPointHistory = recoveryPointHistory; + return this; + } + + /** + * Get the app consistent snapshot frequency in minutes. + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency in minutes. + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the A2APolicyDetails object itself. + */ + public A2APolicyDetails withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get a value indicating whether multi-VM sync has to be enabled. + * + * @return the multiVmSyncStatus value + */ + public String multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi-VM sync has to be enabled. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the A2APolicyDetails object itself. + */ + public A2APolicyDetails withMultiVmSyncStatus(String multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + + /** + * Get the crash consistent snapshot frequency in minutes. + * + * @return the crashConsistentFrequencyInMinutes value + */ + public Integer crashConsistentFrequencyInMinutes() { + return this.crashConsistentFrequencyInMinutes; + } + + /** + * Set the crash consistent snapshot frequency in minutes. + * + * @param crashConsistentFrequencyInMinutes the crashConsistentFrequencyInMinutes value to set + * @return the A2APolicyDetails object itself. + */ + public A2APolicyDetails withCrashConsistentFrequencyInMinutes(Integer crashConsistentFrequencyInMinutes) { + this.crashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectedDiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectedDiskDetails.java new file mode 100644 index 0000000000000..fd167fe0b1e37 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectedDiskDetails.java @@ -0,0 +1,513 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A2A protected disk details. + */ +public class A2AProtectedDiskDetails { + /** + * The disk uri. + */ + @JsonProperty(value = "diskUri") + private String diskUri; + + /** + * The recovery disk storage account. + */ + @JsonProperty(value = "recoveryAzureStorageAccountId") + private String recoveryAzureStorageAccountId; + + /** + * The primary disk storage account. + */ + @JsonProperty(value = "primaryDiskAzureStorageAccountId") + private String primaryDiskAzureStorageAccountId; + + /** + * Recovery disk uri. + */ + @JsonProperty(value = "recoveryDiskUri") + private String recoveryDiskUri; + + /** + * The disk name. + */ + @JsonProperty(value = "diskName") + private String diskName; + + /** + * The disk capacity in bytes. + */ + @JsonProperty(value = "diskCapacityInBytes") + private Long diskCapacityInBytes; + + /** + * The primary staging storage account. + */ + @JsonProperty(value = "primaryStagingAzureStorageAccountId") + private String primaryStagingAzureStorageAccountId; + + /** + * The type of disk. + */ + @JsonProperty(value = "diskType") + private String diskType; + + /** + * A value indicating whether resync is required for this disk. + */ + @JsonProperty(value = "resyncRequired") + private Boolean resyncRequired; + + /** + * The percentage of the monitoring job. The type of the monitoring job is + * defined by MonitoringJobType property. + */ + @JsonProperty(value = "monitoringPercentageCompletion") + private Integer monitoringPercentageCompletion; + + /** + * The type of the monitoring job. The progress is contained in + * MonitoringPercentageCompletion property. + */ + @JsonProperty(value = "monitoringJobType") + private String monitoringJobType; + + /** + * The data pending for replication in MB at staging account. + */ + @JsonProperty(value = "dataPendingInStagingStorageAccountInMB") + private Double dataPendingInStagingStorageAccountInMB; + + /** + * The data pending at source virtual machine in MB. + */ + @JsonProperty(value = "dataPendingAtSourceAgentInMB") + private Double dataPendingAtSourceAgentInMB; + + /** + * A value indicating whether vm has encrypted os disk or not. + */ + @JsonProperty(value = "isDiskEncrypted") + private Boolean isDiskEncrypted; + + /** + * The secret URL / identifier (BEK). + */ + @JsonProperty(value = "secretIdentifier") + private String secretIdentifier; + + /** + * The KeyVault resource id for secret (BEK). + */ + @JsonProperty(value = "dekKeyVaultArmId") + private String dekKeyVaultArmId; + + /** + * A value indicating whether disk key got encrypted or not. + */ + @JsonProperty(value = "isDiskKeyEncrypted") + private Boolean isDiskKeyEncrypted; + + /** + * The key URL / identifier (KEK). + */ + @JsonProperty(value = "keyIdentifier") + private String keyIdentifier; + + /** + * The KeyVault resource id for key (KEK). + */ + @JsonProperty(value = "kekKeyVaultArmId") + private String kekKeyVaultArmId; + + /** + * Get the disk uri. + * + * @return the diskUri value + */ + public String diskUri() { + return this.diskUri; + } + + /** + * Set the disk uri. + * + * @param diskUri the diskUri value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withDiskUri(String diskUri) { + this.diskUri = diskUri; + return this; + } + + /** + * Get the recovery disk storage account. + * + * @return the recoveryAzureStorageAccountId value + */ + public String recoveryAzureStorageAccountId() { + return this.recoveryAzureStorageAccountId; + } + + /** + * Set the recovery disk storage account. + * + * @param recoveryAzureStorageAccountId the recoveryAzureStorageAccountId value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withRecoveryAzureStorageAccountId(String recoveryAzureStorageAccountId) { + this.recoveryAzureStorageAccountId = recoveryAzureStorageAccountId; + return this; + } + + /** + * Get the primary disk storage account. + * + * @return the primaryDiskAzureStorageAccountId value + */ + public String primaryDiskAzureStorageAccountId() { + return this.primaryDiskAzureStorageAccountId; + } + + /** + * Set the primary disk storage account. + * + * @param primaryDiskAzureStorageAccountId the primaryDiskAzureStorageAccountId value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withPrimaryDiskAzureStorageAccountId(String primaryDiskAzureStorageAccountId) { + this.primaryDiskAzureStorageAccountId = primaryDiskAzureStorageAccountId; + return this; + } + + /** + * Get recovery disk uri. + * + * @return the recoveryDiskUri value + */ + public String recoveryDiskUri() { + return this.recoveryDiskUri; + } + + /** + * Set recovery disk uri. + * + * @param recoveryDiskUri the recoveryDiskUri value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withRecoveryDiskUri(String recoveryDiskUri) { + this.recoveryDiskUri = recoveryDiskUri; + return this; + } + + /** + * Get the disk name. + * + * @return the diskName value + */ + public String diskName() { + return this.diskName; + } + + /** + * Set the disk name. + * + * @param diskName the diskName value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withDiskName(String diskName) { + this.diskName = diskName; + return this; + } + + /** + * Get the disk capacity in bytes. + * + * @return the diskCapacityInBytes value + */ + public Long diskCapacityInBytes() { + return this.diskCapacityInBytes; + } + + /** + * Set the disk capacity in bytes. + * + * @param diskCapacityInBytes the diskCapacityInBytes value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withDiskCapacityInBytes(Long diskCapacityInBytes) { + this.diskCapacityInBytes = diskCapacityInBytes; + return this; + } + + /** + * Get the primary staging storage account. + * + * @return the primaryStagingAzureStorageAccountId value + */ + public String primaryStagingAzureStorageAccountId() { + return this.primaryStagingAzureStorageAccountId; + } + + /** + * Set the primary staging storage account. + * + * @param primaryStagingAzureStorageAccountId the primaryStagingAzureStorageAccountId value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withPrimaryStagingAzureStorageAccountId(String primaryStagingAzureStorageAccountId) { + this.primaryStagingAzureStorageAccountId = primaryStagingAzureStorageAccountId; + return this; + } + + /** + * Get the type of disk. + * + * @return the diskType value + */ + public String diskType() { + return this.diskType; + } + + /** + * Set the type of disk. + * + * @param diskType the diskType value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withDiskType(String diskType) { + this.diskType = diskType; + return this; + } + + /** + * Get a value indicating whether resync is required for this disk. + * + * @return the resyncRequired value + */ + public Boolean resyncRequired() { + return this.resyncRequired; + } + + /** + * Set a value indicating whether resync is required for this disk. + * + * @param resyncRequired the resyncRequired value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withResyncRequired(Boolean resyncRequired) { + this.resyncRequired = resyncRequired; + return this; + } + + /** + * Get the percentage of the monitoring job. The type of the monitoring job is defined by MonitoringJobType property. + * + * @return the monitoringPercentageCompletion value + */ + public Integer monitoringPercentageCompletion() { + return this.monitoringPercentageCompletion; + } + + /** + * Set the percentage of the monitoring job. The type of the monitoring job is defined by MonitoringJobType property. + * + * @param monitoringPercentageCompletion the monitoringPercentageCompletion value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withMonitoringPercentageCompletion(Integer monitoringPercentageCompletion) { + this.monitoringPercentageCompletion = monitoringPercentageCompletion; + return this; + } + + /** + * Get the type of the monitoring job. The progress is contained in MonitoringPercentageCompletion property. + * + * @return the monitoringJobType value + */ + public String monitoringJobType() { + return this.monitoringJobType; + } + + /** + * Set the type of the monitoring job. The progress is contained in MonitoringPercentageCompletion property. + * + * @param monitoringJobType the monitoringJobType value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withMonitoringJobType(String monitoringJobType) { + this.monitoringJobType = monitoringJobType; + return this; + } + + /** + * Get the data pending for replication in MB at staging account. + * + * @return the dataPendingInStagingStorageAccountInMB value + */ + public Double dataPendingInStagingStorageAccountInMB() { + return this.dataPendingInStagingStorageAccountInMB; + } + + /** + * Set the data pending for replication in MB at staging account. + * + * @param dataPendingInStagingStorageAccountInMB the dataPendingInStagingStorageAccountInMB value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withDataPendingInStagingStorageAccountInMB(Double dataPendingInStagingStorageAccountInMB) { + this.dataPendingInStagingStorageAccountInMB = dataPendingInStagingStorageAccountInMB; + return this; + } + + /** + * Get the data pending at source virtual machine in MB. + * + * @return the dataPendingAtSourceAgentInMB value + */ + public Double dataPendingAtSourceAgentInMB() { + return this.dataPendingAtSourceAgentInMB; + } + + /** + * Set the data pending at source virtual machine in MB. + * + * @param dataPendingAtSourceAgentInMB the dataPendingAtSourceAgentInMB value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withDataPendingAtSourceAgentInMB(Double dataPendingAtSourceAgentInMB) { + this.dataPendingAtSourceAgentInMB = dataPendingAtSourceAgentInMB; + return this; + } + + /** + * Get a value indicating whether vm has encrypted os disk or not. + * + * @return the isDiskEncrypted value + */ + public Boolean isDiskEncrypted() { + return this.isDiskEncrypted; + } + + /** + * Set a value indicating whether vm has encrypted os disk or not. + * + * @param isDiskEncrypted the isDiskEncrypted value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withIsDiskEncrypted(Boolean isDiskEncrypted) { + this.isDiskEncrypted = isDiskEncrypted; + return this; + } + + /** + * Get the secret URL / identifier (BEK). + * + * @return the secretIdentifier value + */ + public String secretIdentifier() { + return this.secretIdentifier; + } + + /** + * Set the secret URL / identifier (BEK). + * + * @param secretIdentifier the secretIdentifier value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withSecretIdentifier(String secretIdentifier) { + this.secretIdentifier = secretIdentifier; + return this; + } + + /** + * Get the KeyVault resource id for secret (BEK). + * + * @return the dekKeyVaultArmId value + */ + public String dekKeyVaultArmId() { + return this.dekKeyVaultArmId; + } + + /** + * Set the KeyVault resource id for secret (BEK). + * + * @param dekKeyVaultArmId the dekKeyVaultArmId value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withDekKeyVaultArmId(String dekKeyVaultArmId) { + this.dekKeyVaultArmId = dekKeyVaultArmId; + return this; + } + + /** + * Get a value indicating whether disk key got encrypted or not. + * + * @return the isDiskKeyEncrypted value + */ + public Boolean isDiskKeyEncrypted() { + return this.isDiskKeyEncrypted; + } + + /** + * Set a value indicating whether disk key got encrypted or not. + * + * @param isDiskKeyEncrypted the isDiskKeyEncrypted value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withIsDiskKeyEncrypted(Boolean isDiskKeyEncrypted) { + this.isDiskKeyEncrypted = isDiskKeyEncrypted; + return this; + } + + /** + * Get the key URL / identifier (KEK). + * + * @return the keyIdentifier value + */ + public String keyIdentifier() { + return this.keyIdentifier; + } + + /** + * Set the key URL / identifier (KEK). + * + * @param keyIdentifier the keyIdentifier value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withKeyIdentifier(String keyIdentifier) { + this.keyIdentifier = keyIdentifier; + return this; + } + + /** + * Get the KeyVault resource id for key (KEK). + * + * @return the kekKeyVaultArmId value + */ + public String kekKeyVaultArmId() { + return this.kekKeyVaultArmId; + } + + /** + * Set the KeyVault resource id for key (KEK). + * + * @param kekKeyVaultArmId the kekKeyVaultArmId value to set + * @return the A2AProtectedDiskDetails object itself. + */ + public A2AProtectedDiskDetails withKekKeyVaultArmId(String kekKeyVaultArmId) { + this.kekKeyVaultArmId = kekKeyVaultArmId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectedManagedDiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectedManagedDiskDetails.java new file mode 100644 index 0000000000000..eecca9df185cb --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectedManagedDiskDetails.java @@ -0,0 +1,567 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A2A protected managed disk details. + */ +public class A2AProtectedManagedDiskDetails { + /** + * The managed disk Arm id. + */ + @JsonProperty(value = "diskId") + private String diskId; + + /** + * The recovery disk resource group Arm Id. + */ + @JsonProperty(value = "recoveryResourceGroupId") + private String recoveryResourceGroupId; + + /** + * Recovery target disk Arm Id. + */ + @JsonProperty(value = "recoveryTargetDiskId") + private String recoveryTargetDiskId; + + /** + * Recovery replica disk Arm Id. + */ + @JsonProperty(value = "recoveryReplicaDiskId") + private String recoveryReplicaDiskId; + + /** + * The replica disk type. Its an optional value and will be same as source + * disk type if not user provided. + */ + @JsonProperty(value = "recoveryReplicaDiskAccountType") + private String recoveryReplicaDiskAccountType; + + /** + * The target disk type after failover. Its an optional value and will be + * same as source disk type if not user provided. + */ + @JsonProperty(value = "recoveryTargetDiskAccountType") + private String recoveryTargetDiskAccountType; + + /** + * The disk name. + */ + @JsonProperty(value = "diskName") + private String diskName; + + /** + * The disk capacity in bytes. + */ + @JsonProperty(value = "diskCapacityInBytes") + private Long diskCapacityInBytes; + + /** + * The primary staging storage account. + */ + @JsonProperty(value = "primaryStagingAzureStorageAccountId") + private String primaryStagingAzureStorageAccountId; + + /** + * The type of disk. + */ + @JsonProperty(value = "diskType") + private String diskType; + + /** + * A value indicating whether resync is required for this disk. + */ + @JsonProperty(value = "resyncRequired") + private Boolean resyncRequired; + + /** + * The percentage of the monitoring job. The type of the monitoring job is + * defined by MonitoringJobType property. + */ + @JsonProperty(value = "monitoringPercentageCompletion") + private Integer monitoringPercentageCompletion; + + /** + * The type of the monitoring job. The progress is contained in + * MonitoringPercentageCompletion property. + */ + @JsonProperty(value = "monitoringJobType") + private String monitoringJobType; + + /** + * The data pending for replication in MB at staging account. + */ + @JsonProperty(value = "dataPendingInStagingStorageAccountInMB") + private Double dataPendingInStagingStorageAccountInMB; + + /** + * The data pending at source virtual machine in MB. + */ + @JsonProperty(value = "dataPendingAtSourceAgentInMB") + private Double dataPendingAtSourceAgentInMB; + + /** + * A value indicating whether vm has encrypted os disk or not. + */ + @JsonProperty(value = "isDiskEncrypted") + private Boolean isDiskEncrypted; + + /** + * The secret URL / identifier (BEK). + */ + @JsonProperty(value = "secretIdentifier") + private String secretIdentifier; + + /** + * The KeyVault resource id for secret (BEK). + */ + @JsonProperty(value = "dekKeyVaultArmId") + private String dekKeyVaultArmId; + + /** + * A value indicating whether disk key got encrypted or not. + */ + @JsonProperty(value = "isDiskKeyEncrypted") + private Boolean isDiskKeyEncrypted; + + /** + * The key URL / identifier (KEK). + */ + @JsonProperty(value = "keyIdentifier") + private String keyIdentifier; + + /** + * The KeyVault resource id for key (KEK). + */ + @JsonProperty(value = "kekKeyVaultArmId") + private String kekKeyVaultArmId; + + /** + * Get the managed disk Arm id. + * + * @return the diskId value + */ + public String diskId() { + return this.diskId; + } + + /** + * Set the managed disk Arm id. + * + * @param diskId the diskId value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withDiskId(String diskId) { + this.diskId = diskId; + return this; + } + + /** + * Get the recovery disk resource group Arm Id. + * + * @return the recoveryResourceGroupId value + */ + public String recoveryResourceGroupId() { + return this.recoveryResourceGroupId; + } + + /** + * Set the recovery disk resource group Arm Id. + * + * @param recoveryResourceGroupId the recoveryResourceGroupId value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withRecoveryResourceGroupId(String recoveryResourceGroupId) { + this.recoveryResourceGroupId = recoveryResourceGroupId; + return this; + } + + /** + * Get recovery target disk Arm Id. + * + * @return the recoveryTargetDiskId value + */ + public String recoveryTargetDiskId() { + return this.recoveryTargetDiskId; + } + + /** + * Set recovery target disk Arm Id. + * + * @param recoveryTargetDiskId the recoveryTargetDiskId value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withRecoveryTargetDiskId(String recoveryTargetDiskId) { + this.recoveryTargetDiskId = recoveryTargetDiskId; + return this; + } + + /** + * Get recovery replica disk Arm Id. + * + * @return the recoveryReplicaDiskId value + */ + public String recoveryReplicaDiskId() { + return this.recoveryReplicaDiskId; + } + + /** + * Set recovery replica disk Arm Id. + * + * @param recoveryReplicaDiskId the recoveryReplicaDiskId value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withRecoveryReplicaDiskId(String recoveryReplicaDiskId) { + this.recoveryReplicaDiskId = recoveryReplicaDiskId; + return this; + } + + /** + * Get the replica disk type. Its an optional value and will be same as source disk type if not user provided. + * + * @return the recoveryReplicaDiskAccountType value + */ + public String recoveryReplicaDiskAccountType() { + return this.recoveryReplicaDiskAccountType; + } + + /** + * Set the replica disk type. Its an optional value and will be same as source disk type if not user provided. + * + * @param recoveryReplicaDiskAccountType the recoveryReplicaDiskAccountType value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withRecoveryReplicaDiskAccountType(String recoveryReplicaDiskAccountType) { + this.recoveryReplicaDiskAccountType = recoveryReplicaDiskAccountType; + return this; + } + + /** + * Get the target disk type after failover. Its an optional value and will be same as source disk type if not user provided. + * + * @return the recoveryTargetDiskAccountType value + */ + public String recoveryTargetDiskAccountType() { + return this.recoveryTargetDiskAccountType; + } + + /** + * Set the target disk type after failover. Its an optional value and will be same as source disk type if not user provided. + * + * @param recoveryTargetDiskAccountType the recoveryTargetDiskAccountType value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withRecoveryTargetDiskAccountType(String recoveryTargetDiskAccountType) { + this.recoveryTargetDiskAccountType = recoveryTargetDiskAccountType; + return this; + } + + /** + * Get the disk name. + * + * @return the diskName value + */ + public String diskName() { + return this.diskName; + } + + /** + * Set the disk name. + * + * @param diskName the diskName value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withDiskName(String diskName) { + this.diskName = diskName; + return this; + } + + /** + * Get the disk capacity in bytes. + * + * @return the diskCapacityInBytes value + */ + public Long diskCapacityInBytes() { + return this.diskCapacityInBytes; + } + + /** + * Set the disk capacity in bytes. + * + * @param diskCapacityInBytes the diskCapacityInBytes value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withDiskCapacityInBytes(Long diskCapacityInBytes) { + this.diskCapacityInBytes = diskCapacityInBytes; + return this; + } + + /** + * Get the primary staging storage account. + * + * @return the primaryStagingAzureStorageAccountId value + */ + public String primaryStagingAzureStorageAccountId() { + return this.primaryStagingAzureStorageAccountId; + } + + /** + * Set the primary staging storage account. + * + * @param primaryStagingAzureStorageAccountId the primaryStagingAzureStorageAccountId value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withPrimaryStagingAzureStorageAccountId(String primaryStagingAzureStorageAccountId) { + this.primaryStagingAzureStorageAccountId = primaryStagingAzureStorageAccountId; + return this; + } + + /** + * Get the type of disk. + * + * @return the diskType value + */ + public String diskType() { + return this.diskType; + } + + /** + * Set the type of disk. + * + * @param diskType the diskType value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withDiskType(String diskType) { + this.diskType = diskType; + return this; + } + + /** + * Get a value indicating whether resync is required for this disk. + * + * @return the resyncRequired value + */ + public Boolean resyncRequired() { + return this.resyncRequired; + } + + /** + * Set a value indicating whether resync is required for this disk. + * + * @param resyncRequired the resyncRequired value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withResyncRequired(Boolean resyncRequired) { + this.resyncRequired = resyncRequired; + return this; + } + + /** + * Get the percentage of the monitoring job. The type of the monitoring job is defined by MonitoringJobType property. + * + * @return the monitoringPercentageCompletion value + */ + public Integer monitoringPercentageCompletion() { + return this.monitoringPercentageCompletion; + } + + /** + * Set the percentage of the monitoring job. The type of the monitoring job is defined by MonitoringJobType property. + * + * @param monitoringPercentageCompletion the monitoringPercentageCompletion value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withMonitoringPercentageCompletion(Integer monitoringPercentageCompletion) { + this.monitoringPercentageCompletion = monitoringPercentageCompletion; + return this; + } + + /** + * Get the type of the monitoring job. The progress is contained in MonitoringPercentageCompletion property. + * + * @return the monitoringJobType value + */ + public String monitoringJobType() { + return this.monitoringJobType; + } + + /** + * Set the type of the monitoring job. The progress is contained in MonitoringPercentageCompletion property. + * + * @param monitoringJobType the monitoringJobType value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withMonitoringJobType(String monitoringJobType) { + this.monitoringJobType = monitoringJobType; + return this; + } + + /** + * Get the data pending for replication in MB at staging account. + * + * @return the dataPendingInStagingStorageAccountInMB value + */ + public Double dataPendingInStagingStorageAccountInMB() { + return this.dataPendingInStagingStorageAccountInMB; + } + + /** + * Set the data pending for replication in MB at staging account. + * + * @param dataPendingInStagingStorageAccountInMB the dataPendingInStagingStorageAccountInMB value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withDataPendingInStagingStorageAccountInMB(Double dataPendingInStagingStorageAccountInMB) { + this.dataPendingInStagingStorageAccountInMB = dataPendingInStagingStorageAccountInMB; + return this; + } + + /** + * Get the data pending at source virtual machine in MB. + * + * @return the dataPendingAtSourceAgentInMB value + */ + public Double dataPendingAtSourceAgentInMB() { + return this.dataPendingAtSourceAgentInMB; + } + + /** + * Set the data pending at source virtual machine in MB. + * + * @param dataPendingAtSourceAgentInMB the dataPendingAtSourceAgentInMB value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withDataPendingAtSourceAgentInMB(Double dataPendingAtSourceAgentInMB) { + this.dataPendingAtSourceAgentInMB = dataPendingAtSourceAgentInMB; + return this; + } + + /** + * Get a value indicating whether vm has encrypted os disk or not. + * + * @return the isDiskEncrypted value + */ + public Boolean isDiskEncrypted() { + return this.isDiskEncrypted; + } + + /** + * Set a value indicating whether vm has encrypted os disk or not. + * + * @param isDiskEncrypted the isDiskEncrypted value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withIsDiskEncrypted(Boolean isDiskEncrypted) { + this.isDiskEncrypted = isDiskEncrypted; + return this; + } + + /** + * Get the secret URL / identifier (BEK). + * + * @return the secretIdentifier value + */ + public String secretIdentifier() { + return this.secretIdentifier; + } + + /** + * Set the secret URL / identifier (BEK). + * + * @param secretIdentifier the secretIdentifier value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withSecretIdentifier(String secretIdentifier) { + this.secretIdentifier = secretIdentifier; + return this; + } + + /** + * Get the KeyVault resource id for secret (BEK). + * + * @return the dekKeyVaultArmId value + */ + public String dekKeyVaultArmId() { + return this.dekKeyVaultArmId; + } + + /** + * Set the KeyVault resource id for secret (BEK). + * + * @param dekKeyVaultArmId the dekKeyVaultArmId value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withDekKeyVaultArmId(String dekKeyVaultArmId) { + this.dekKeyVaultArmId = dekKeyVaultArmId; + return this; + } + + /** + * Get a value indicating whether disk key got encrypted or not. + * + * @return the isDiskKeyEncrypted value + */ + public Boolean isDiskKeyEncrypted() { + return this.isDiskKeyEncrypted; + } + + /** + * Set a value indicating whether disk key got encrypted or not. + * + * @param isDiskKeyEncrypted the isDiskKeyEncrypted value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withIsDiskKeyEncrypted(Boolean isDiskKeyEncrypted) { + this.isDiskKeyEncrypted = isDiskKeyEncrypted; + return this; + } + + /** + * Get the key URL / identifier (KEK). + * + * @return the keyIdentifier value + */ + public String keyIdentifier() { + return this.keyIdentifier; + } + + /** + * Set the key URL / identifier (KEK). + * + * @param keyIdentifier the keyIdentifier value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withKeyIdentifier(String keyIdentifier) { + this.keyIdentifier = keyIdentifier; + return this; + } + + /** + * Get the KeyVault resource id for key (KEK). + * + * @return the kekKeyVaultArmId value + */ + public String kekKeyVaultArmId() { + return this.kekKeyVaultArmId; + } + + /** + * Set the KeyVault resource id for key (KEK). + * + * @param kekKeyVaultArmId the kekKeyVaultArmId value to set + * @return the A2AProtectedManagedDiskDetails object itself. + */ + public A2AProtectedManagedDiskDetails withKekKeyVaultArmId(String kekKeyVaultArmId) { + this.kekKeyVaultArmId = kekKeyVaultArmId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectionContainerMappingDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectionContainerMappingDetails.java new file mode 100644 index 0000000000000..257d194e2bb2e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AProtectionContainerMappingDetails.java @@ -0,0 +1,126 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AProtectionContainerMappingDetails extends ProtectionContainerMappingProviderSpecificDetails { + /** + * A value indicating whether the auto update is enabled. Possible values + * include: 'Disabled', 'Enabled'. + */ + @JsonProperty(value = "agentAutoUpdateStatus") + private AgentAutoUpdateStatus agentAutoUpdateStatus; + + /** + * The automation account arm id. + */ + @JsonProperty(value = "automationAccountArmId") + private String automationAccountArmId; + + /** + * The schedule arm name. + */ + @JsonProperty(value = "scheduleName") + private String scheduleName; + + /** + * The job schedule arm name. + */ + @JsonProperty(value = "jobScheduleName") + private String jobScheduleName; + + /** + * Get a value indicating whether the auto update is enabled. Possible values include: 'Disabled', 'Enabled'. + * + * @return the agentAutoUpdateStatus value + */ + public AgentAutoUpdateStatus agentAutoUpdateStatus() { + return this.agentAutoUpdateStatus; + } + + /** + * Set a value indicating whether the auto update is enabled. Possible values include: 'Disabled', 'Enabled'. + * + * @param agentAutoUpdateStatus the agentAutoUpdateStatus value to set + * @return the A2AProtectionContainerMappingDetails object itself. + */ + public A2AProtectionContainerMappingDetails withAgentAutoUpdateStatus(AgentAutoUpdateStatus agentAutoUpdateStatus) { + this.agentAutoUpdateStatus = agentAutoUpdateStatus; + return this; + } + + /** + * Get the automation account arm id. + * + * @return the automationAccountArmId value + */ + public String automationAccountArmId() { + return this.automationAccountArmId; + } + + /** + * Set the automation account arm id. + * + * @param automationAccountArmId the automationAccountArmId value to set + * @return the A2AProtectionContainerMappingDetails object itself. + */ + public A2AProtectionContainerMappingDetails withAutomationAccountArmId(String automationAccountArmId) { + this.automationAccountArmId = automationAccountArmId; + return this; + } + + /** + * Get the schedule arm name. + * + * @return the scheduleName value + */ + public String scheduleName() { + return this.scheduleName; + } + + /** + * Set the schedule arm name. + * + * @param scheduleName the scheduleName value to set + * @return the A2AProtectionContainerMappingDetails object itself. + */ + public A2AProtectionContainerMappingDetails withScheduleName(String scheduleName) { + this.scheduleName = scheduleName; + return this; + } + + /** + * Get the job schedule arm name. + * + * @return the jobScheduleName value + */ + public String jobScheduleName() { + return this.jobScheduleName; + } + + /** + * Set the job schedule arm name. + * + * @param jobScheduleName the jobScheduleName value to set + * @return the A2AProtectionContainerMappingDetails object itself. + */ + public A2AProtectionContainerMappingDetails withJobScheduleName(String jobScheduleName) { + this.jobScheduleName = jobScheduleName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ARecoveryPointDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ARecoveryPointDetails.java new file mode 100644 index 0000000000000..aa0d24f8e7f9b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ARecoveryPointDetails.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A provider specific recovery point details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2ARecoveryPointDetails extends ProviderSpecificRecoveryPointDetails { + /** + * A value indicating whether the recovery point is multi VM consistent. + * Possible values include: 'MultiVmSyncRecoveryPoint', + * 'PerVmRecoveryPoint'. + */ + @JsonProperty(value = "recoveryPointSyncType") + private RecoveryPointSyncType recoveryPointSyncType; + + /** + * Get a value indicating whether the recovery point is multi VM consistent. Possible values include: 'MultiVmSyncRecoveryPoint', 'PerVmRecoveryPoint'. + * + * @return the recoveryPointSyncType value + */ + public RecoveryPointSyncType recoveryPointSyncType() { + return this.recoveryPointSyncType; + } + + /** + * Set a value indicating whether the recovery point is multi VM consistent. Possible values include: 'MultiVmSyncRecoveryPoint', 'PerVmRecoveryPoint'. + * + * @param recoveryPointSyncType the recoveryPointSyncType value to set + * @return the A2ARecoveryPointDetails object itself. + */ + public A2ARecoveryPointDetails withRecoveryPointSyncType(RecoveryPointSyncType recoveryPointSyncType) { + this.recoveryPointSyncType = recoveryPointSyncType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AReplicationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AReplicationDetails.java new file mode 100644 index 0000000000000..dc91682cf39e2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AReplicationDetails.java @@ -0,0 +1,837 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AReplicationDetails extends ReplicationProviderSpecificSettings { + /** + * The fabric specific object Id of the virtual machine. + */ + @JsonProperty(value = "fabricObjectId") + private String fabricObjectId; + + /** + * The multi vm group Id. + */ + @JsonProperty(value = "multiVmGroupId") + private String multiVmGroupId; + + /** + * The multi vm group name. + */ + @JsonProperty(value = "multiVmGroupName") + private String multiVmGroupName; + + /** + * Whether Multi VM group is auto created or specified by user. Possible + * values include: 'AutoCreated', 'UserSpecified'. + */ + @JsonProperty(value = "multiVmGroupCreateOption") + private MultiVmGroupCreateOption multiVmGroupCreateOption; + + /** + * The management Id. + */ + @JsonProperty(value = "managementId") + private String managementId; + + /** + * The list of protected disks. + */ + @JsonProperty(value = "protectedDisks") + private List protectedDisks; + + /** + * The list of protected managed disks. + */ + @JsonProperty(value = "protectedManagedDisks") + private List protectedManagedDisks; + + /** + * The recovery boot diagnostic storage account Arm Id. + */ + @JsonProperty(value = "recoveryBootDiagStorageAccountId") + private String recoveryBootDiagStorageAccountId; + + /** + * Primary fabric location. + */ + @JsonProperty(value = "primaryFabricLocation") + private String primaryFabricLocation; + + /** + * The recovery fabric location. + */ + @JsonProperty(value = "recoveryFabricLocation") + private String recoveryFabricLocation; + + /** + * The type of operating system. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * The size of recovery virtual machine. + */ + @JsonProperty(value = "recoveryAzureVMSize") + private String recoveryAzureVMSize; + + /** + * The name of recovery virtual machine. + */ + @JsonProperty(value = "recoveryAzureVMName") + private String recoveryAzureVMName; + + /** + * The recovery resource group. + */ + @JsonProperty(value = "recoveryAzureResourceGroupId") + private String recoveryAzureResourceGroupId; + + /** + * The recovery cloud service. + */ + @JsonProperty(value = "recoveryCloudService") + private String recoveryCloudService; + + /** + * The recovery availability set. + */ + @JsonProperty(value = "recoveryAvailabilitySet") + private String recoveryAvailabilitySet; + + /** + * The recovery virtual network. + */ + @JsonProperty(value = "selectedRecoveryAzureNetworkId") + private String selectedRecoveryAzureNetworkId; + + /** + * The virtual machine nic details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * The synced configuration details. + */ + @JsonProperty(value = "vmSyncedConfigDetails") + private AzureToAzureVmSyncedConfigDetails vmSyncedConfigDetails; + + /** + * The percentage of the monitoring job. The type of the monitoring job is + * defined by MonitoringJobType property. + */ + @JsonProperty(value = "monitoringPercentageCompletion") + private Integer monitoringPercentageCompletion; + + /** + * The type of the monitoring job. The progress is contained in + * MonitoringPercentageCompletion property. + */ + @JsonProperty(value = "monitoringJobType") + private String monitoringJobType; + + /** + * The last heartbeat received from the source server. + */ + @JsonProperty(value = "lastHeartbeat") + private DateTime lastHeartbeat; + + /** + * The agent version. + */ + @JsonProperty(value = "agentVersion") + private String agentVersion; + + /** + * A value indicating whether replication agent update is required. + */ + @JsonProperty(value = "isReplicationAgentUpdateRequired") + private Boolean isReplicationAgentUpdateRequired; + + /** + * The recovery fabric object Id. + */ + @JsonProperty(value = "recoveryFabricObjectId") + private String recoveryFabricObjectId; + + /** + * The protection state for the vm. + */ + @JsonProperty(value = "vmProtectionState") + private String vmProtectionState; + + /** + * The protection state description for the vm. + */ + @JsonProperty(value = "vmProtectionStateDescription") + private String vmProtectionStateDescription; + + /** + * An id associated with the PE that survives actions like switch + * protection which change the backing PE/CPE objects internally.The + * lifecycle id gets carried forward to have a link/continuity in being + * able to have an Id that denotes the "same" protected item even though + * other internal Ids/ARM Id might be changing. + */ + @JsonProperty(value = "lifecycleId") + private String lifecycleId; + + /** + * The test failover fabric object Id. + */ + @JsonProperty(value = "testFailoverRecoveryFabricObjectId") + private String testFailoverRecoveryFabricObjectId; + + /** + * The last RPO value in seconds. + */ + @JsonProperty(value = "rpoInSeconds") + private Long rpoInSeconds; + + /** + * The time (in UTC) when the last RPO value was calculated by Protection + * Service. + */ + @JsonProperty(value = "lastRpoCalculatedTime") + private DateTime lastRpoCalculatedTime; + + /** + * Get the fabric specific object Id of the virtual machine. + * + * @return the fabricObjectId value + */ + public String fabricObjectId() { + return this.fabricObjectId; + } + + /** + * Set the fabric specific object Id of the virtual machine. + * + * @param fabricObjectId the fabricObjectId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withFabricObjectId(String fabricObjectId) { + this.fabricObjectId = fabricObjectId; + return this; + } + + /** + * Get the multi vm group Id. + * + * @return the multiVmGroupId value + */ + public String multiVmGroupId() { + return this.multiVmGroupId; + } + + /** + * Set the multi vm group Id. + * + * @param multiVmGroupId the multiVmGroupId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withMultiVmGroupId(String multiVmGroupId) { + this.multiVmGroupId = multiVmGroupId; + return this; + } + + /** + * Get the multi vm group name. + * + * @return the multiVmGroupName value + */ + public String multiVmGroupName() { + return this.multiVmGroupName; + } + + /** + * Set the multi vm group name. + * + * @param multiVmGroupName the multiVmGroupName value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withMultiVmGroupName(String multiVmGroupName) { + this.multiVmGroupName = multiVmGroupName; + return this; + } + + /** + * Get whether Multi VM group is auto created or specified by user. Possible values include: 'AutoCreated', 'UserSpecified'. + * + * @return the multiVmGroupCreateOption value + */ + public MultiVmGroupCreateOption multiVmGroupCreateOption() { + return this.multiVmGroupCreateOption; + } + + /** + * Set whether Multi VM group is auto created or specified by user. Possible values include: 'AutoCreated', 'UserSpecified'. + * + * @param multiVmGroupCreateOption the multiVmGroupCreateOption value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withMultiVmGroupCreateOption(MultiVmGroupCreateOption multiVmGroupCreateOption) { + this.multiVmGroupCreateOption = multiVmGroupCreateOption; + return this; + } + + /** + * Get the management Id. + * + * @return the managementId value + */ + public String managementId() { + return this.managementId; + } + + /** + * Set the management Id. + * + * @param managementId the managementId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withManagementId(String managementId) { + this.managementId = managementId; + return this; + } + + /** + * Get the list of protected disks. + * + * @return the protectedDisks value + */ + public List protectedDisks() { + return this.protectedDisks; + } + + /** + * Set the list of protected disks. + * + * @param protectedDisks the protectedDisks value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withProtectedDisks(List protectedDisks) { + this.protectedDisks = protectedDisks; + return this; + } + + /** + * Get the list of protected managed disks. + * + * @return the protectedManagedDisks value + */ + public List protectedManagedDisks() { + return this.protectedManagedDisks; + } + + /** + * Set the list of protected managed disks. + * + * @param protectedManagedDisks the protectedManagedDisks value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withProtectedManagedDisks(List protectedManagedDisks) { + this.protectedManagedDisks = protectedManagedDisks; + return this; + } + + /** + * Get the recovery boot diagnostic storage account Arm Id. + * + * @return the recoveryBootDiagStorageAccountId value + */ + public String recoveryBootDiagStorageAccountId() { + return this.recoveryBootDiagStorageAccountId; + } + + /** + * Set the recovery boot diagnostic storage account Arm Id. + * + * @param recoveryBootDiagStorageAccountId the recoveryBootDiagStorageAccountId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRecoveryBootDiagStorageAccountId(String recoveryBootDiagStorageAccountId) { + this.recoveryBootDiagStorageAccountId = recoveryBootDiagStorageAccountId; + return this; + } + + /** + * Get primary fabric location. + * + * @return the primaryFabricLocation value + */ + public String primaryFabricLocation() { + return this.primaryFabricLocation; + } + + /** + * Set primary fabric location. + * + * @param primaryFabricLocation the primaryFabricLocation value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withPrimaryFabricLocation(String primaryFabricLocation) { + this.primaryFabricLocation = primaryFabricLocation; + return this; + } + + /** + * Get the recovery fabric location. + * + * @return the recoveryFabricLocation value + */ + public String recoveryFabricLocation() { + return this.recoveryFabricLocation; + } + + /** + * Set the recovery fabric location. + * + * @param recoveryFabricLocation the recoveryFabricLocation value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRecoveryFabricLocation(String recoveryFabricLocation) { + this.recoveryFabricLocation = recoveryFabricLocation; + return this; + } + + /** + * Get the type of operating system. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the type of operating system. + * + * @param osType the osType value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get the size of recovery virtual machine. + * + * @return the recoveryAzureVMSize value + */ + public String recoveryAzureVMSize() { + return this.recoveryAzureVMSize; + } + + /** + * Set the size of recovery virtual machine. + * + * @param recoveryAzureVMSize the recoveryAzureVMSize value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRecoveryAzureVMSize(String recoveryAzureVMSize) { + this.recoveryAzureVMSize = recoveryAzureVMSize; + return this; + } + + /** + * Get the name of recovery virtual machine. + * + * @return the recoveryAzureVMName value + */ + public String recoveryAzureVMName() { + return this.recoveryAzureVMName; + } + + /** + * Set the name of recovery virtual machine. + * + * @param recoveryAzureVMName the recoveryAzureVMName value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRecoveryAzureVMName(String recoveryAzureVMName) { + this.recoveryAzureVMName = recoveryAzureVMName; + return this; + } + + /** + * Get the recovery resource group. + * + * @return the recoveryAzureResourceGroupId value + */ + public String recoveryAzureResourceGroupId() { + return this.recoveryAzureResourceGroupId; + } + + /** + * Set the recovery resource group. + * + * @param recoveryAzureResourceGroupId the recoveryAzureResourceGroupId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRecoveryAzureResourceGroupId(String recoveryAzureResourceGroupId) { + this.recoveryAzureResourceGroupId = recoveryAzureResourceGroupId; + return this; + } + + /** + * Get the recovery cloud service. + * + * @return the recoveryCloudService value + */ + public String recoveryCloudService() { + return this.recoveryCloudService; + } + + /** + * Set the recovery cloud service. + * + * @param recoveryCloudService the recoveryCloudService value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRecoveryCloudService(String recoveryCloudService) { + this.recoveryCloudService = recoveryCloudService; + return this; + } + + /** + * Get the recovery availability set. + * + * @return the recoveryAvailabilitySet value + */ + public String recoveryAvailabilitySet() { + return this.recoveryAvailabilitySet; + } + + /** + * Set the recovery availability set. + * + * @param recoveryAvailabilitySet the recoveryAvailabilitySet value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRecoveryAvailabilitySet(String recoveryAvailabilitySet) { + this.recoveryAvailabilitySet = recoveryAvailabilitySet; + return this; + } + + /** + * Get the recovery virtual network. + * + * @return the selectedRecoveryAzureNetworkId value + */ + public String selectedRecoveryAzureNetworkId() { + return this.selectedRecoveryAzureNetworkId; + } + + /** + * Set the recovery virtual network. + * + * @param selectedRecoveryAzureNetworkId the selectedRecoveryAzureNetworkId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withSelectedRecoveryAzureNetworkId(String selectedRecoveryAzureNetworkId) { + this.selectedRecoveryAzureNetworkId = selectedRecoveryAzureNetworkId; + return this; + } + + /** + * Get the virtual machine nic details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the virtual machine nic details. + * + * @param vmNics the vmNics value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get the synced configuration details. + * + * @return the vmSyncedConfigDetails value + */ + public AzureToAzureVmSyncedConfigDetails vmSyncedConfigDetails() { + return this.vmSyncedConfigDetails; + } + + /** + * Set the synced configuration details. + * + * @param vmSyncedConfigDetails the vmSyncedConfigDetails value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withVmSyncedConfigDetails(AzureToAzureVmSyncedConfigDetails vmSyncedConfigDetails) { + this.vmSyncedConfigDetails = vmSyncedConfigDetails; + return this; + } + + /** + * Get the percentage of the monitoring job. The type of the monitoring job is defined by MonitoringJobType property. + * + * @return the monitoringPercentageCompletion value + */ + public Integer monitoringPercentageCompletion() { + return this.monitoringPercentageCompletion; + } + + /** + * Set the percentage of the monitoring job. The type of the monitoring job is defined by MonitoringJobType property. + * + * @param monitoringPercentageCompletion the monitoringPercentageCompletion value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withMonitoringPercentageCompletion(Integer monitoringPercentageCompletion) { + this.monitoringPercentageCompletion = monitoringPercentageCompletion; + return this; + } + + /** + * Get the type of the monitoring job. The progress is contained in MonitoringPercentageCompletion property. + * + * @return the monitoringJobType value + */ + public String monitoringJobType() { + return this.monitoringJobType; + } + + /** + * Set the type of the monitoring job. The progress is contained in MonitoringPercentageCompletion property. + * + * @param monitoringJobType the monitoringJobType value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withMonitoringJobType(String monitoringJobType) { + this.monitoringJobType = monitoringJobType; + return this; + } + + /** + * Get the last heartbeat received from the source server. + * + * @return the lastHeartbeat value + */ + public DateTime lastHeartbeat() { + return this.lastHeartbeat; + } + + /** + * Set the last heartbeat received from the source server. + * + * @param lastHeartbeat the lastHeartbeat value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withLastHeartbeat(DateTime lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + return this; + } + + /** + * Get the agent version. + * + * @return the agentVersion value + */ + public String agentVersion() { + return this.agentVersion; + } + + /** + * Set the agent version. + * + * @param agentVersion the agentVersion value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withAgentVersion(String agentVersion) { + this.agentVersion = agentVersion; + return this; + } + + /** + * Get a value indicating whether replication agent update is required. + * + * @return the isReplicationAgentUpdateRequired value + */ + public Boolean isReplicationAgentUpdateRequired() { + return this.isReplicationAgentUpdateRequired; + } + + /** + * Set a value indicating whether replication agent update is required. + * + * @param isReplicationAgentUpdateRequired the isReplicationAgentUpdateRequired value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withIsReplicationAgentUpdateRequired(Boolean isReplicationAgentUpdateRequired) { + this.isReplicationAgentUpdateRequired = isReplicationAgentUpdateRequired; + return this; + } + + /** + * Get the recovery fabric object Id. + * + * @return the recoveryFabricObjectId value + */ + public String recoveryFabricObjectId() { + return this.recoveryFabricObjectId; + } + + /** + * Set the recovery fabric object Id. + * + * @param recoveryFabricObjectId the recoveryFabricObjectId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRecoveryFabricObjectId(String recoveryFabricObjectId) { + this.recoveryFabricObjectId = recoveryFabricObjectId; + return this; + } + + /** + * Get the protection state for the vm. + * + * @return the vmProtectionState value + */ + public String vmProtectionState() { + return this.vmProtectionState; + } + + /** + * Set the protection state for the vm. + * + * @param vmProtectionState the vmProtectionState value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withVmProtectionState(String vmProtectionState) { + this.vmProtectionState = vmProtectionState; + return this; + } + + /** + * Get the protection state description for the vm. + * + * @return the vmProtectionStateDescription value + */ + public String vmProtectionStateDescription() { + return this.vmProtectionStateDescription; + } + + /** + * Set the protection state description for the vm. + * + * @param vmProtectionStateDescription the vmProtectionStateDescription value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withVmProtectionStateDescription(String vmProtectionStateDescription) { + this.vmProtectionStateDescription = vmProtectionStateDescription; + return this; + } + + /** + * Get an id associated with the PE that survives actions like switch protection which change the backing PE/CPE objects internally.The lifecycle id gets carried forward to have a link/continuity in being able to have an Id that denotes the "same" protected item even though other internal Ids/ARM Id might be changing. + * + * @return the lifecycleId value + */ + public String lifecycleId() { + return this.lifecycleId; + } + + /** + * Set an id associated with the PE that survives actions like switch protection which change the backing PE/CPE objects internally.The lifecycle id gets carried forward to have a link/continuity in being able to have an Id that denotes the "same" protected item even though other internal Ids/ARM Id might be changing. + * + * @param lifecycleId the lifecycleId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withLifecycleId(String lifecycleId) { + this.lifecycleId = lifecycleId; + return this; + } + + /** + * Get the test failover fabric object Id. + * + * @return the testFailoverRecoveryFabricObjectId value + */ + public String testFailoverRecoveryFabricObjectId() { + return this.testFailoverRecoveryFabricObjectId; + } + + /** + * Set the test failover fabric object Id. + * + * @param testFailoverRecoveryFabricObjectId the testFailoverRecoveryFabricObjectId value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withTestFailoverRecoveryFabricObjectId(String testFailoverRecoveryFabricObjectId) { + this.testFailoverRecoveryFabricObjectId = testFailoverRecoveryFabricObjectId; + return this; + } + + /** + * Get the last RPO value in seconds. + * + * @return the rpoInSeconds value + */ + public Long rpoInSeconds() { + return this.rpoInSeconds; + } + + /** + * Set the last RPO value in seconds. + * + * @param rpoInSeconds the rpoInSeconds value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withRpoInSeconds(Long rpoInSeconds) { + this.rpoInSeconds = rpoInSeconds; + return this; + } + + /** + * Get the time (in UTC) when the last RPO value was calculated by Protection Service. + * + * @return the lastRpoCalculatedTime value + */ + public DateTime lastRpoCalculatedTime() { + return this.lastRpoCalculatedTime; + } + + /** + * Set the time (in UTC) when the last RPO value was calculated by Protection Service. + * + * @param lastRpoCalculatedTime the lastRpoCalculatedTime value to set + * @return the A2AReplicationDetails object itself. + */ + public A2AReplicationDetails withLastRpoCalculatedTime(DateTime lastRpoCalculatedTime) { + this.lastRpoCalculatedTime = lastRpoCalculatedTime; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AReprotectInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AReprotectInput.java new file mode 100644 index 0000000000000..a29cebeb4f46d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AReprotectInput.java @@ -0,0 +1,178 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Azure specific reprotect input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AReprotectInput extends ReverseReplicationProviderSpecificInput { + /** + * The recovery container Id. + */ + @JsonProperty(value = "recoveryContainerId") + private String recoveryContainerId; + + /** + * The list of vm disk details. + */ + @JsonProperty(value = "vmDisks") + private List vmDisks; + + /** + * The recovery resource group Id. Valid for V2 scenarios. + */ + @JsonProperty(value = "recoveryResourceGroupId") + private String recoveryResourceGroupId; + + /** + * The recovery cloud service Id. Valid for V1 scenarios. + */ + @JsonProperty(value = "recoveryCloudServiceId") + private String recoveryCloudServiceId; + + /** + * The recovery availability set. + */ + @JsonProperty(value = "recoveryAvailabilitySetId") + private String recoveryAvailabilitySetId; + + /** + * The Policy Id. + */ + @JsonProperty(value = "policyId") + private String policyId; + + /** + * Get the recovery container Id. + * + * @return the recoveryContainerId value + */ + public String recoveryContainerId() { + return this.recoveryContainerId; + } + + /** + * Set the recovery container Id. + * + * @param recoveryContainerId the recoveryContainerId value to set + * @return the A2AReprotectInput object itself. + */ + public A2AReprotectInput withRecoveryContainerId(String recoveryContainerId) { + this.recoveryContainerId = recoveryContainerId; + return this; + } + + /** + * Get the list of vm disk details. + * + * @return the vmDisks value + */ + public List vmDisks() { + return this.vmDisks; + } + + /** + * Set the list of vm disk details. + * + * @param vmDisks the vmDisks value to set + * @return the A2AReprotectInput object itself. + */ + public A2AReprotectInput withVmDisks(List vmDisks) { + this.vmDisks = vmDisks; + return this; + } + + /** + * Get the recovery resource group Id. Valid for V2 scenarios. + * + * @return the recoveryResourceGroupId value + */ + public String recoveryResourceGroupId() { + return this.recoveryResourceGroupId; + } + + /** + * Set the recovery resource group Id. Valid for V2 scenarios. + * + * @param recoveryResourceGroupId the recoveryResourceGroupId value to set + * @return the A2AReprotectInput object itself. + */ + public A2AReprotectInput withRecoveryResourceGroupId(String recoveryResourceGroupId) { + this.recoveryResourceGroupId = recoveryResourceGroupId; + return this; + } + + /** + * Get the recovery cloud service Id. Valid for V1 scenarios. + * + * @return the recoveryCloudServiceId value + */ + public String recoveryCloudServiceId() { + return this.recoveryCloudServiceId; + } + + /** + * Set the recovery cloud service Id. Valid for V1 scenarios. + * + * @param recoveryCloudServiceId the recoveryCloudServiceId value to set + * @return the A2AReprotectInput object itself. + */ + public A2AReprotectInput withRecoveryCloudServiceId(String recoveryCloudServiceId) { + this.recoveryCloudServiceId = recoveryCloudServiceId; + return this; + } + + /** + * Get the recovery availability set. + * + * @return the recoveryAvailabilitySetId value + */ + public String recoveryAvailabilitySetId() { + return this.recoveryAvailabilitySetId; + } + + /** + * Set the recovery availability set. + * + * @param recoveryAvailabilitySetId the recoveryAvailabilitySetId value to set + * @return the A2AReprotectInput object itself. + */ + public A2AReprotectInput withRecoveryAvailabilitySetId(String recoveryAvailabilitySetId) { + this.recoveryAvailabilitySetId = recoveryAvailabilitySetId; + return this; + } + + /** + * Get the Policy Id. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Set the Policy Id. + * + * @param policyId the policyId value to set + * @return the A2AReprotectInput object itself. + */ + public A2AReprotectInput withPolicyId(String policyId) { + this.policyId = policyId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ARpRecoveryPointType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ARpRecoveryPointType.java new file mode 100644 index 0000000000000..5438ab51a0fc2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ARpRecoveryPointType.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for A2ARpRecoveryPointType. + */ +public final class A2ARpRecoveryPointType extends ExpandableStringEnum { + /** Static value Latest for A2ARpRecoveryPointType. */ + public static final A2ARpRecoveryPointType LATEST = fromString("Latest"); + + /** Static value LatestApplicationConsistent for A2ARpRecoveryPointType. */ + public static final A2ARpRecoveryPointType LATEST_APPLICATION_CONSISTENT = fromString("LatestApplicationConsistent"); + + /** Static value LatestCrashConsistent for A2ARpRecoveryPointType. */ + public static final A2ARpRecoveryPointType LATEST_CRASH_CONSISTENT = fromString("LatestCrashConsistent"); + + /** Static value LatestProcessed for A2ARpRecoveryPointType. */ + public static final A2ARpRecoveryPointType LATEST_PROCESSED = fromString("LatestProcessed"); + + /** + * Creates or finds a A2ARpRecoveryPointType from its string representation. + * @param name a name to look for + * @return the corresponding A2ARpRecoveryPointType + */ + @JsonCreator + public static A2ARpRecoveryPointType fromString(String name) { + return fromString(name, A2ARpRecoveryPointType.class); + } + + /** + * @return known A2ARpRecoveryPointType values + */ + public static Collection values() { + return values(A2ARpRecoveryPointType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ASwitchProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ASwitchProtectionInput.java new file mode 100644 index 0000000000000..3b6688a7170aa --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2ASwitchProtectionInput.java @@ -0,0 +1,256 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A specific switch protection input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2ASwitchProtectionInput extends SwitchProtectionProviderSpecificInput { + /** + * The recovery container Id. + */ + @JsonProperty(value = "recoveryContainerId") + private String recoveryContainerId; + + /** + * The list of vm disk details. + */ + @JsonProperty(value = "vmDisks") + private List vmDisks; + + /** + * The list of vm managed disk details. + */ + @JsonProperty(value = "vmManagedDisks") + private List vmManagedDisks; + + /** + * The recovery resource group Id. Valid for V2 scenarios. + */ + @JsonProperty(value = "recoveryResourceGroupId") + private String recoveryResourceGroupId; + + /** + * The recovery cloud service Id. Valid for V1 scenarios. + */ + @JsonProperty(value = "recoveryCloudServiceId") + private String recoveryCloudServiceId; + + /** + * The recovery availability set. + */ + @JsonProperty(value = "recoveryAvailabilitySetId") + private String recoveryAvailabilitySetId; + + /** + * The Policy Id. + */ + @JsonProperty(value = "policyId") + private String policyId; + + /** + * The boot diagnostic storage account. + */ + @JsonProperty(value = "recoveryBootDiagStorageAccountId") + private String recoveryBootDiagStorageAccountId; + + /** + * The recovery disk encryption information. + */ + @JsonProperty(value = "diskEncryptionInfo") + private DiskEncryptionInfo diskEncryptionInfo; + + /** + * Get the recovery container Id. + * + * @return the recoveryContainerId value + */ + public String recoveryContainerId() { + return this.recoveryContainerId; + } + + /** + * Set the recovery container Id. + * + * @param recoveryContainerId the recoveryContainerId value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withRecoveryContainerId(String recoveryContainerId) { + this.recoveryContainerId = recoveryContainerId; + return this; + } + + /** + * Get the list of vm disk details. + * + * @return the vmDisks value + */ + public List vmDisks() { + return this.vmDisks; + } + + /** + * Set the list of vm disk details. + * + * @param vmDisks the vmDisks value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withVmDisks(List vmDisks) { + this.vmDisks = vmDisks; + return this; + } + + /** + * Get the list of vm managed disk details. + * + * @return the vmManagedDisks value + */ + public List vmManagedDisks() { + return this.vmManagedDisks; + } + + /** + * Set the list of vm managed disk details. + * + * @param vmManagedDisks the vmManagedDisks value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withVmManagedDisks(List vmManagedDisks) { + this.vmManagedDisks = vmManagedDisks; + return this; + } + + /** + * Get the recovery resource group Id. Valid for V2 scenarios. + * + * @return the recoveryResourceGroupId value + */ + public String recoveryResourceGroupId() { + return this.recoveryResourceGroupId; + } + + /** + * Set the recovery resource group Id. Valid for V2 scenarios. + * + * @param recoveryResourceGroupId the recoveryResourceGroupId value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withRecoveryResourceGroupId(String recoveryResourceGroupId) { + this.recoveryResourceGroupId = recoveryResourceGroupId; + return this; + } + + /** + * Get the recovery cloud service Id. Valid for V1 scenarios. + * + * @return the recoveryCloudServiceId value + */ + public String recoveryCloudServiceId() { + return this.recoveryCloudServiceId; + } + + /** + * Set the recovery cloud service Id. Valid for V1 scenarios. + * + * @param recoveryCloudServiceId the recoveryCloudServiceId value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withRecoveryCloudServiceId(String recoveryCloudServiceId) { + this.recoveryCloudServiceId = recoveryCloudServiceId; + return this; + } + + /** + * Get the recovery availability set. + * + * @return the recoveryAvailabilitySetId value + */ + public String recoveryAvailabilitySetId() { + return this.recoveryAvailabilitySetId; + } + + /** + * Set the recovery availability set. + * + * @param recoveryAvailabilitySetId the recoveryAvailabilitySetId value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withRecoveryAvailabilitySetId(String recoveryAvailabilitySetId) { + this.recoveryAvailabilitySetId = recoveryAvailabilitySetId; + return this; + } + + /** + * Get the Policy Id. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Set the Policy Id. + * + * @param policyId the policyId value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withPolicyId(String policyId) { + this.policyId = policyId; + return this; + } + + /** + * Get the boot diagnostic storage account. + * + * @return the recoveryBootDiagStorageAccountId value + */ + public String recoveryBootDiagStorageAccountId() { + return this.recoveryBootDiagStorageAccountId; + } + + /** + * Set the boot diagnostic storage account. + * + * @param recoveryBootDiagStorageAccountId the recoveryBootDiagStorageAccountId value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withRecoveryBootDiagStorageAccountId(String recoveryBootDiagStorageAccountId) { + this.recoveryBootDiagStorageAccountId = recoveryBootDiagStorageAccountId; + return this; + } + + /** + * Get the recovery disk encryption information. + * + * @return the diskEncryptionInfo value + */ + public DiskEncryptionInfo diskEncryptionInfo() { + return this.diskEncryptionInfo; + } + + /** + * Set the recovery disk encryption information. + * + * @param diskEncryptionInfo the diskEncryptionInfo value to set + * @return the A2ASwitchProtectionInput object itself. + */ + public A2ASwitchProtectionInput withDiskEncryptionInfo(DiskEncryptionInfo diskEncryptionInfo) { + this.diskEncryptionInfo = diskEncryptionInfo; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AUpdateContainerMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AUpdateContainerMappingInput.java new file mode 100644 index 0000000000000..7a52e911ad65f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AUpdateContainerMappingInput.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A update protection container mapping. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AUpdateContainerMappingInput extends ReplicationProviderSpecificUpdateContainerMappingInput { + /** + * A value indicating whether the auto update is enabled. Possible values + * include: 'Disabled', 'Enabled'. + */ + @JsonProperty(value = "agentAutoUpdateStatus") + private AgentAutoUpdateStatus agentAutoUpdateStatus; + + /** + * The automation account arm id. + */ + @JsonProperty(value = "automationAccountArmId") + private String automationAccountArmId; + + /** + * Get a value indicating whether the auto update is enabled. Possible values include: 'Disabled', 'Enabled'. + * + * @return the agentAutoUpdateStatus value + */ + public AgentAutoUpdateStatus agentAutoUpdateStatus() { + return this.agentAutoUpdateStatus; + } + + /** + * Set a value indicating whether the auto update is enabled. Possible values include: 'Disabled', 'Enabled'. + * + * @param agentAutoUpdateStatus the agentAutoUpdateStatus value to set + * @return the A2AUpdateContainerMappingInput object itself. + */ + public A2AUpdateContainerMappingInput withAgentAutoUpdateStatus(AgentAutoUpdateStatus agentAutoUpdateStatus) { + this.agentAutoUpdateStatus = agentAutoUpdateStatus; + return this; + } + + /** + * Get the automation account arm id. + * + * @return the automationAccountArmId value + */ + public String automationAccountArmId() { + return this.automationAccountArmId; + } + + /** + * Set the automation account arm id. + * + * @param automationAccountArmId the automationAccountArmId value to set + * @return the A2AUpdateContainerMappingInput object itself. + */ + public A2AUpdateContainerMappingInput withAutomationAccountArmId(String automationAccountArmId) { + this.automationAccountArmId = automationAccountArmId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AUpdateReplicationProtectedItemInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AUpdateReplicationProtectedItemInput.java new file mode 100644 index 0000000000000..2224aaddfc39f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AUpdateReplicationProtectedItemInput.java @@ -0,0 +1,152 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMage Azure V2 input to update replication protected item. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class A2AUpdateReplicationProtectedItemInput extends UpdateReplicationProtectedItemProviderInput { + /** + * The target cloud service ARM Id (for V1). + */ + @JsonProperty(value = "recoveryCloudServiceId") + private String recoveryCloudServiceId; + + /** + * The target resource group ARM Id (for V2). + */ + @JsonProperty(value = "recoveryResourceGroupId") + private String recoveryResourceGroupId; + + /** + * Managed disk update details. + */ + @JsonProperty(value = "managedDiskUpdateDetails") + private List managedDiskUpdateDetails; + + /** + * The boot diagnostic storage account. + */ + @JsonProperty(value = "recoveryBootDiagStorageAccountId") + private String recoveryBootDiagStorageAccountId; + + /** + * The recovery os disk encryption information. + */ + @JsonProperty(value = "diskEncryptionInfo") + private DiskEncryptionInfo diskEncryptionInfo; + + /** + * Get the target cloud service ARM Id (for V1). + * + * @return the recoveryCloudServiceId value + */ + public String recoveryCloudServiceId() { + return this.recoveryCloudServiceId; + } + + /** + * Set the target cloud service ARM Id (for V1). + * + * @param recoveryCloudServiceId the recoveryCloudServiceId value to set + * @return the A2AUpdateReplicationProtectedItemInput object itself. + */ + public A2AUpdateReplicationProtectedItemInput withRecoveryCloudServiceId(String recoveryCloudServiceId) { + this.recoveryCloudServiceId = recoveryCloudServiceId; + return this; + } + + /** + * Get the target resource group ARM Id (for V2). + * + * @return the recoveryResourceGroupId value + */ + public String recoveryResourceGroupId() { + return this.recoveryResourceGroupId; + } + + /** + * Set the target resource group ARM Id (for V2). + * + * @param recoveryResourceGroupId the recoveryResourceGroupId value to set + * @return the A2AUpdateReplicationProtectedItemInput object itself. + */ + public A2AUpdateReplicationProtectedItemInput withRecoveryResourceGroupId(String recoveryResourceGroupId) { + this.recoveryResourceGroupId = recoveryResourceGroupId; + return this; + } + + /** + * Get managed disk update details. + * + * @return the managedDiskUpdateDetails value + */ + public List managedDiskUpdateDetails() { + return this.managedDiskUpdateDetails; + } + + /** + * Set managed disk update details. + * + * @param managedDiskUpdateDetails the managedDiskUpdateDetails value to set + * @return the A2AUpdateReplicationProtectedItemInput object itself. + */ + public A2AUpdateReplicationProtectedItemInput withManagedDiskUpdateDetails(List managedDiskUpdateDetails) { + this.managedDiskUpdateDetails = managedDiskUpdateDetails; + return this; + } + + /** + * Get the boot diagnostic storage account. + * + * @return the recoveryBootDiagStorageAccountId value + */ + public String recoveryBootDiagStorageAccountId() { + return this.recoveryBootDiagStorageAccountId; + } + + /** + * Set the boot diagnostic storage account. + * + * @param recoveryBootDiagStorageAccountId the recoveryBootDiagStorageAccountId value to set + * @return the A2AUpdateReplicationProtectedItemInput object itself. + */ + public A2AUpdateReplicationProtectedItemInput withRecoveryBootDiagStorageAccountId(String recoveryBootDiagStorageAccountId) { + this.recoveryBootDiagStorageAccountId = recoveryBootDiagStorageAccountId; + return this; + } + + /** + * Get the recovery os disk encryption information. + * + * @return the diskEncryptionInfo value + */ + public DiskEncryptionInfo diskEncryptionInfo() { + return this.diskEncryptionInfo; + } + + /** + * Set the recovery os disk encryption information. + * + * @param diskEncryptionInfo the diskEncryptionInfo value to set + * @return the A2AUpdateReplicationProtectedItemInput object itself. + */ + public A2AUpdateReplicationProtectedItemInput withDiskEncryptionInfo(DiskEncryptionInfo diskEncryptionInfo) { + this.diskEncryptionInfo = diskEncryptionInfo; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmDiskInputDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmDiskInputDetails.java new file mode 100644 index 0000000000000..9857b5ec7281a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmDiskInputDetails.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Azure VM disk input details. + */ +public class A2AVmDiskInputDetails { + /** + * The disk Uri. + */ + @JsonProperty(value = "diskUri") + private String diskUri; + + /** + * The recovery VHD storage account Id. + */ + @JsonProperty(value = "recoveryAzureStorageAccountId") + private String recoveryAzureStorageAccountId; + + /** + * The primary staging storage account Id. + */ + @JsonProperty(value = "primaryStagingAzureStorageAccountId") + private String primaryStagingAzureStorageAccountId; + + /** + * Get the disk Uri. + * + * @return the diskUri value + */ + public String diskUri() { + return this.diskUri; + } + + /** + * Set the disk Uri. + * + * @param diskUri the diskUri value to set + * @return the A2AVmDiskInputDetails object itself. + */ + public A2AVmDiskInputDetails withDiskUri(String diskUri) { + this.diskUri = diskUri; + return this; + } + + /** + * Get the recovery VHD storage account Id. + * + * @return the recoveryAzureStorageAccountId value + */ + public String recoveryAzureStorageAccountId() { + return this.recoveryAzureStorageAccountId; + } + + /** + * Set the recovery VHD storage account Id. + * + * @param recoveryAzureStorageAccountId the recoveryAzureStorageAccountId value to set + * @return the A2AVmDiskInputDetails object itself. + */ + public A2AVmDiskInputDetails withRecoveryAzureStorageAccountId(String recoveryAzureStorageAccountId) { + this.recoveryAzureStorageAccountId = recoveryAzureStorageAccountId; + return this; + } + + /** + * Get the primary staging storage account Id. + * + * @return the primaryStagingAzureStorageAccountId value + */ + public String primaryStagingAzureStorageAccountId() { + return this.primaryStagingAzureStorageAccountId; + } + + /** + * Set the primary staging storage account Id. + * + * @param primaryStagingAzureStorageAccountId the primaryStagingAzureStorageAccountId value to set + * @return the A2AVmDiskInputDetails object itself. + */ + public A2AVmDiskInputDetails withPrimaryStagingAzureStorageAccountId(String primaryStagingAzureStorageAccountId) { + this.primaryStagingAzureStorageAccountId = primaryStagingAzureStorageAccountId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmManagedDiskInputDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmManagedDiskInputDetails.java new file mode 100644 index 0000000000000..8eb29d38eec30 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmManagedDiskInputDetails.java @@ -0,0 +1,149 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Azure VM managed disk input details. + */ +public class A2AVmManagedDiskInputDetails { + /** + * The disk Id. + */ + @JsonProperty(value = "diskId") + private String diskId; + + /** + * The primary staging storage account Arm Id. + */ + @JsonProperty(value = "primaryStagingAzureStorageAccountId") + private String primaryStagingAzureStorageAccountId; + + /** + * The target resource group Arm Id. + */ + @JsonProperty(value = "recoveryResourceGroupId") + private String recoveryResourceGroupId; + + /** + * The replica disk type. Its an optional value and will be same as source + * disk type if not user provided. + */ + @JsonProperty(value = "recoveryReplicaDiskAccountType") + private String recoveryReplicaDiskAccountType; + + /** + * The target disk type after failover. Its an optional value and will be + * same as source disk type if not user provided. + */ + @JsonProperty(value = "recoveryTargetDiskAccountType") + private String recoveryTargetDiskAccountType; + + /** + * Get the disk Id. + * + * @return the diskId value + */ + public String diskId() { + return this.diskId; + } + + /** + * Set the disk Id. + * + * @param diskId the diskId value to set + * @return the A2AVmManagedDiskInputDetails object itself. + */ + public A2AVmManagedDiskInputDetails withDiskId(String diskId) { + this.diskId = diskId; + return this; + } + + /** + * Get the primary staging storage account Arm Id. + * + * @return the primaryStagingAzureStorageAccountId value + */ + public String primaryStagingAzureStorageAccountId() { + return this.primaryStagingAzureStorageAccountId; + } + + /** + * Set the primary staging storage account Arm Id. + * + * @param primaryStagingAzureStorageAccountId the primaryStagingAzureStorageAccountId value to set + * @return the A2AVmManagedDiskInputDetails object itself. + */ + public A2AVmManagedDiskInputDetails withPrimaryStagingAzureStorageAccountId(String primaryStagingAzureStorageAccountId) { + this.primaryStagingAzureStorageAccountId = primaryStagingAzureStorageAccountId; + return this; + } + + /** + * Get the target resource group Arm Id. + * + * @return the recoveryResourceGroupId value + */ + public String recoveryResourceGroupId() { + return this.recoveryResourceGroupId; + } + + /** + * Set the target resource group Arm Id. + * + * @param recoveryResourceGroupId the recoveryResourceGroupId value to set + * @return the A2AVmManagedDiskInputDetails object itself. + */ + public A2AVmManagedDiskInputDetails withRecoveryResourceGroupId(String recoveryResourceGroupId) { + this.recoveryResourceGroupId = recoveryResourceGroupId; + return this; + } + + /** + * Get the replica disk type. Its an optional value and will be same as source disk type if not user provided. + * + * @return the recoveryReplicaDiskAccountType value + */ + public String recoveryReplicaDiskAccountType() { + return this.recoveryReplicaDiskAccountType; + } + + /** + * Set the replica disk type. Its an optional value and will be same as source disk type if not user provided. + * + * @param recoveryReplicaDiskAccountType the recoveryReplicaDiskAccountType value to set + * @return the A2AVmManagedDiskInputDetails object itself. + */ + public A2AVmManagedDiskInputDetails withRecoveryReplicaDiskAccountType(String recoveryReplicaDiskAccountType) { + this.recoveryReplicaDiskAccountType = recoveryReplicaDiskAccountType; + return this; + } + + /** + * Get the target disk type after failover. Its an optional value and will be same as source disk type if not user provided. + * + * @return the recoveryTargetDiskAccountType value + */ + public String recoveryTargetDiskAccountType() { + return this.recoveryTargetDiskAccountType; + } + + /** + * Set the target disk type after failover. Its an optional value and will be same as source disk type if not user provided. + * + * @param recoveryTargetDiskAccountType the recoveryTargetDiskAccountType value to set + * @return the A2AVmManagedDiskInputDetails object itself. + */ + public A2AVmManagedDiskInputDetails withRecoveryTargetDiskAccountType(String recoveryTargetDiskAccountType) { + this.recoveryTargetDiskAccountType = recoveryTargetDiskAccountType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmManagedDiskUpdateDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmManagedDiskUpdateDetails.java new file mode 100644 index 0000000000000..fa965587ed3e1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/A2AVmManagedDiskUpdateDetails.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Azure VM managed disk update input details. + */ +public class A2AVmManagedDiskUpdateDetails { + /** + * The disk Id. + */ + @JsonProperty(value = "diskId") + private String diskId; + + /** + * The target disk type before failover. + */ + @JsonProperty(value = "recoveryTargetDiskAccountType") + private String recoveryTargetDiskAccountType; + + /** + * The replica disk type before failover. + */ + @JsonProperty(value = "recoveryReplicaDiskAccountType") + private String recoveryReplicaDiskAccountType; + + /** + * Get the disk Id. + * + * @return the diskId value + */ + public String diskId() { + return this.diskId; + } + + /** + * Set the disk Id. + * + * @param diskId the diskId value to set + * @return the A2AVmManagedDiskUpdateDetails object itself. + */ + public A2AVmManagedDiskUpdateDetails withDiskId(String diskId) { + this.diskId = diskId; + return this; + } + + /** + * Get the target disk type before failover. + * + * @return the recoveryTargetDiskAccountType value + */ + public String recoveryTargetDiskAccountType() { + return this.recoveryTargetDiskAccountType; + } + + /** + * Set the target disk type before failover. + * + * @param recoveryTargetDiskAccountType the recoveryTargetDiskAccountType value to set + * @return the A2AVmManagedDiskUpdateDetails object itself. + */ + public A2AVmManagedDiskUpdateDetails withRecoveryTargetDiskAccountType(String recoveryTargetDiskAccountType) { + this.recoveryTargetDiskAccountType = recoveryTargetDiskAccountType; + return this; + } + + /** + * Get the replica disk type before failover. + * + * @return the recoveryReplicaDiskAccountType value + */ + public String recoveryReplicaDiskAccountType() { + return this.recoveryReplicaDiskAccountType; + } + + /** + * Set the replica disk type before failover. + * + * @param recoveryReplicaDiskAccountType the recoveryReplicaDiskAccountType value to set + * @return the A2AVmManagedDiskUpdateDetails object itself. + */ + public A2AVmManagedDiskUpdateDetails withRecoveryReplicaDiskAccountType(String recoveryReplicaDiskAccountType) { + this.recoveryReplicaDiskAccountType = recoveryReplicaDiskAccountType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ASRTask.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ASRTask.java new file mode 100644 index 0000000000000..c866c1408c4ad --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ASRTask.java @@ -0,0 +1,335 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Task of the Job. + */ +public class ASRTask { + /** + * The Id. + */ + @JsonProperty(value = "taskId") + private String taskId; + + /** + * The unique Task name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The start time. + */ + @JsonProperty(value = "startTime") + private DateTime startTime; + + /** + * The end time. + */ + @JsonProperty(value = "endTime") + private DateTime endTime; + + /** + * The state/actions applicable on this task. + */ + @JsonProperty(value = "allowedActions") + private List allowedActions; + + /** + * The name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The State. It is one of these values - NotStarted, InProgress, + * Succeeded, Failed, Cancelled, Suspended or Other. + */ + @JsonProperty(value = "state") + private String state; + + /** + * The description of the task state. For example - For Succeeded state, + * description can be Completed, PartiallySucceeded, + * CompletedWithInformation or Skipped. + */ + @JsonProperty(value = "stateDescription") + private String stateDescription; + + /** + * The type of task. Details in CustomDetails property depend on this type. + */ + @JsonProperty(value = "taskType") + private String taskType; + + /** + * The custom task details based on the task type. + */ + @JsonProperty(value = "customDetails") + private TaskTypeDetails customDetails; + + /** + * The custom task details based on the task type, if the task type is + * GroupTaskDetails or one of the types derived from it. + */ + @JsonProperty(value = "groupTaskCustomDetails") + private GroupTaskDetails groupTaskCustomDetails; + + /** + * The task error details. + */ + @JsonProperty(value = "errors") + private List errors; + + /** + * Get the Id. + * + * @return the taskId value + */ + public String taskId() { + return this.taskId; + } + + /** + * Set the Id. + * + * @param taskId the taskId value to set + * @return the ASRTask object itself. + */ + public ASRTask withTaskId(String taskId) { + this.taskId = taskId; + return this; + } + + /** + * Get the unique Task name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the unique Task name. + * + * @param name the name value to set + * @return the ASRTask object itself. + */ + public ASRTask withName(String name) { + this.name = name; + return this; + } + + /** + * Get the start time. + * + * @return the startTime value + */ + public DateTime startTime() { + return this.startTime; + } + + /** + * Set the start time. + * + * @param startTime the startTime value to set + * @return the ASRTask object itself. + */ + public ASRTask withStartTime(DateTime startTime) { + this.startTime = startTime; + return this; + } + + /** + * Get the end time. + * + * @return the endTime value + */ + public DateTime endTime() { + return this.endTime; + } + + /** + * Set the end time. + * + * @param endTime the endTime value to set + * @return the ASRTask object itself. + */ + public ASRTask withEndTime(DateTime endTime) { + this.endTime = endTime; + return this; + } + + /** + * Get the state/actions applicable on this task. + * + * @return the allowedActions value + */ + public List allowedActions() { + return this.allowedActions; + } + + /** + * Set the state/actions applicable on this task. + * + * @param allowedActions the allowedActions value to set + * @return the ASRTask object itself. + */ + public ASRTask withAllowedActions(List allowedActions) { + this.allowedActions = allowedActions; + return this; + } + + /** + * Get the name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the name. + * + * @param friendlyName the friendlyName value to set + * @return the ASRTask object itself. + */ + public ASRTask withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the State. It is one of these values - NotStarted, InProgress, Succeeded, Failed, Cancelled, Suspended or Other. + * + * @return the state value + */ + public String state() { + return this.state; + } + + /** + * Set the State. It is one of these values - NotStarted, InProgress, Succeeded, Failed, Cancelled, Suspended or Other. + * + * @param state the state value to set + * @return the ASRTask object itself. + */ + public ASRTask withState(String state) { + this.state = state; + return this; + } + + /** + * Get the description of the task state. For example - For Succeeded state, description can be Completed, PartiallySucceeded, CompletedWithInformation or Skipped. + * + * @return the stateDescription value + */ + public String stateDescription() { + return this.stateDescription; + } + + /** + * Set the description of the task state. For example - For Succeeded state, description can be Completed, PartiallySucceeded, CompletedWithInformation or Skipped. + * + * @param stateDescription the stateDescription value to set + * @return the ASRTask object itself. + */ + public ASRTask withStateDescription(String stateDescription) { + this.stateDescription = stateDescription; + return this; + } + + /** + * Get the type of task. Details in CustomDetails property depend on this type. + * + * @return the taskType value + */ + public String taskType() { + return this.taskType; + } + + /** + * Set the type of task. Details in CustomDetails property depend on this type. + * + * @param taskType the taskType value to set + * @return the ASRTask object itself. + */ + public ASRTask withTaskType(String taskType) { + this.taskType = taskType; + return this; + } + + /** + * Get the custom task details based on the task type. + * + * @return the customDetails value + */ + public TaskTypeDetails customDetails() { + return this.customDetails; + } + + /** + * Set the custom task details based on the task type. + * + * @param customDetails the customDetails value to set + * @return the ASRTask object itself. + */ + public ASRTask withCustomDetails(TaskTypeDetails customDetails) { + this.customDetails = customDetails; + return this; + } + + /** + * Get the custom task details based on the task type, if the task type is GroupTaskDetails or one of the types derived from it. + * + * @return the groupTaskCustomDetails value + */ + public GroupTaskDetails groupTaskCustomDetails() { + return this.groupTaskCustomDetails; + } + + /** + * Set the custom task details based on the task type, if the task type is GroupTaskDetails or one of the types derived from it. + * + * @param groupTaskCustomDetails the groupTaskCustomDetails value to set + * @return the ASRTask object itself. + */ + public ASRTask withGroupTaskCustomDetails(GroupTaskDetails groupTaskCustomDetails) { + this.groupTaskCustomDetails = groupTaskCustomDetails; + return this; + } + + /** + * Get the task error details. + * + * @return the errors value + */ + public List errors() { + return this.errors; + } + + /** + * Set the task error details. + * + * @param errors the errors value to set + * @return the ASRTask object itself. + */ + public ASRTask withErrors(List errors) { + this.errors = errors; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddRecoveryServicesProviderInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddRecoveryServicesProviderInput.java new file mode 100644 index 0000000000000..27dd4bed0b8f6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddRecoveryServicesProviderInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input required to add a provider. + */ +public class AddRecoveryServicesProviderInput { + /** + * The properties of an add provider request. + */ + @JsonProperty(value = "properties", required = true) + private AddRecoveryServicesProviderInputProperties properties; + + /** + * Get the properties of an add provider request. + * + * @return the properties value + */ + public AddRecoveryServicesProviderInputProperties properties() { + return this.properties; + } + + /** + * Set the properties of an add provider request. + * + * @param properties the properties value to set + * @return the AddRecoveryServicesProviderInput object itself. + */ + public AddRecoveryServicesProviderInput withProperties(AddRecoveryServicesProviderInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddRecoveryServicesProviderInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddRecoveryServicesProviderInputProperties.java new file mode 100644 index 0000000000000..ea1137050c9a7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddRecoveryServicesProviderInputProperties.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The properties of an add provider request. + */ +public class AddRecoveryServicesProviderInputProperties { + /** + * The name of the machine where the provider is getting added. + */ + @JsonProperty(value = "machineName", required = true) + private String machineName; + + /** + * The identity provider input for DRA authentication. + */ + @JsonProperty(value = "authenticationIdentityInput", required = true) + private IdentityProviderInput authenticationIdentityInput; + + /** + * The identity provider input for resource access. + */ + @JsonProperty(value = "resourceAccessIdentityInput", required = true) + private IdentityProviderInput resourceAccessIdentityInput; + + /** + * Get the name of the machine where the provider is getting added. + * + * @return the machineName value + */ + public String machineName() { + return this.machineName; + } + + /** + * Set the name of the machine where the provider is getting added. + * + * @param machineName the machineName value to set + * @return the AddRecoveryServicesProviderInputProperties object itself. + */ + public AddRecoveryServicesProviderInputProperties withMachineName(String machineName) { + this.machineName = machineName; + return this; + } + + /** + * Get the identity provider input for DRA authentication. + * + * @return the authenticationIdentityInput value + */ + public IdentityProviderInput authenticationIdentityInput() { + return this.authenticationIdentityInput; + } + + /** + * Set the identity provider input for DRA authentication. + * + * @param authenticationIdentityInput the authenticationIdentityInput value to set + * @return the AddRecoveryServicesProviderInputProperties object itself. + */ + public AddRecoveryServicesProviderInputProperties withAuthenticationIdentityInput(IdentityProviderInput authenticationIdentityInput) { + this.authenticationIdentityInput = authenticationIdentityInput; + return this; + } + + /** + * Get the identity provider input for resource access. + * + * @return the resourceAccessIdentityInput value + */ + public IdentityProviderInput resourceAccessIdentityInput() { + return this.resourceAccessIdentityInput; + } + + /** + * Set the identity provider input for resource access. + * + * @param resourceAccessIdentityInput the resourceAccessIdentityInput value to set + * @return the AddRecoveryServicesProviderInputProperties object itself. + */ + public AddRecoveryServicesProviderInputProperties withResourceAccessIdentityInput(IdentityProviderInput resourceAccessIdentityInput) { + this.resourceAccessIdentityInput = resourceAccessIdentityInput; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddVCenterRequest.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddVCenterRequest.java new file mode 100644 index 0000000000000..23123e93a27d1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddVCenterRequest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input required to add vCenter. + */ +public class AddVCenterRequest { + /** + * The properties of an add vCenter request. + */ + @JsonProperty(value = "properties") + private AddVCenterRequestProperties properties; + + /** + * Get the properties of an add vCenter request. + * + * @return the properties value + */ + public AddVCenterRequestProperties properties() { + return this.properties; + } + + /** + * Set the properties of an add vCenter request. + * + * @param properties the properties value to set + * @return the AddVCenterRequest object itself. + */ + public AddVCenterRequest withProperties(AddVCenterRequestProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddVCenterRequestProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddVCenterRequestProperties.java new file mode 100644 index 0000000000000..9b22ac46684ae --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AddVCenterRequestProperties.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The properties of an add vCenter request. + */ +public class AddVCenterRequestProperties { + /** + * The friendly name of the vCenter. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The IP address of the vCenter to be discovered. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The process server Id from where the discovery is orchestrated. + */ + @JsonProperty(value = "processServerId") + private String processServerId; + + /** + * The port number for discovery. + */ + @JsonProperty(value = "port") + private String port; + + /** + * The account Id which has privileges to discover the vCenter. + */ + @JsonProperty(value = "runAsAccountId") + private String runAsAccountId; + + /** + * Get the friendly name of the vCenter. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the friendly name of the vCenter. + * + * @param friendlyName the friendlyName value to set + * @return the AddVCenterRequestProperties object itself. + */ + public AddVCenterRequestProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the IP address of the vCenter to be discovered. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the IP address of the vCenter to be discovered. + * + * @param ipAddress the ipAddress value to set + * @return the AddVCenterRequestProperties object itself. + */ + public AddVCenterRequestProperties withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the process server Id from where the discovery is orchestrated. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the process server Id from where the discovery is orchestrated. + * + * @param processServerId the processServerId value to set + * @return the AddVCenterRequestProperties object itself. + */ + public AddVCenterRequestProperties withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the port number for discovery. + * + * @return the port value + */ + public String port() { + return this.port; + } + + /** + * Set the port number for discovery. + * + * @param port the port value to set + * @return the AddVCenterRequestProperties object itself. + */ + public AddVCenterRequestProperties withPort(String port) { + this.port = port; + return this; + } + + /** + * Get the account Id which has privileges to discover the vCenter. + * + * @return the runAsAccountId value + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Set the account Id which has privileges to discover the vCenter. + * + * @param runAsAccountId the runAsAccountId value to set + * @return the AddVCenterRequestProperties object itself. + */ + public AddVCenterRequestProperties withRunAsAccountId(String runAsAccountId) { + this.runAsAccountId = runAsAccountId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AgentAutoUpdateStatus.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AgentAutoUpdateStatus.java new file mode 100644 index 0000000000000..0d5b3f66dd109 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AgentAutoUpdateStatus.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for AgentAutoUpdateStatus. + */ +public final class AgentAutoUpdateStatus extends ExpandableStringEnum { + /** Static value Disabled for AgentAutoUpdateStatus. */ + public static final AgentAutoUpdateStatus DISABLED = fromString("Disabled"); + + /** Static value Enabled for AgentAutoUpdateStatus. */ + public static final AgentAutoUpdateStatus ENABLED = fromString("Enabled"); + + /** + * Creates or finds a AgentAutoUpdateStatus from its string representation. + * @param name a name to look for + * @return the corresponding AgentAutoUpdateStatus + */ + @JsonCreator + public static AgentAutoUpdateStatus fromString(String name) { + return fromString(name, AgentAutoUpdateStatus.class); + } + + /** + * @return known AgentAutoUpdateStatus values + */ + public static Collection values() { + return values(AgentAutoUpdateStatus.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AgentVersionStatus.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AgentVersionStatus.java new file mode 100644 index 0000000000000..04faf1a32810c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AgentVersionStatus.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for AgentVersionStatus. + */ +public final class AgentVersionStatus extends ExpandableStringEnum { + /** Static value Supported for AgentVersionStatus. */ + public static final AgentVersionStatus SUPPORTED = fromString("Supported"); + + /** Static value NotSupported for AgentVersionStatus. */ + public static final AgentVersionStatus NOT_SUPPORTED = fromString("NotSupported"); + + /** Static value Deprecated for AgentVersionStatus. */ + public static final AgentVersionStatus DEPRECATED = fromString("Deprecated"); + + /** Static value UpdateRequired for AgentVersionStatus. */ + public static final AgentVersionStatus UPDATE_REQUIRED = fromString("UpdateRequired"); + + /** Static value SecurityUpdateRequired for AgentVersionStatus. */ + public static final AgentVersionStatus SECURITY_UPDATE_REQUIRED = fromString("SecurityUpdateRequired"); + + /** + * Creates or finds a AgentVersionStatus from its string representation. + * @param name a name to look for + * @return the corresponding AgentVersionStatus + */ + @JsonCreator + public static AgentVersionStatus fromString(String name) { + return fromString(name, AgentVersionStatus.class); + } + + /** + * @return known AgentVersionStatus values + */ + public static Collection values() { + return values(AgentVersionStatus.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Alert.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Alert.java new file mode 100644 index 0000000000000..9d42e41ac01ab --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Alert.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.AlertInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; +import java.util.List; + +/** + * Type representing Alert. + */ +public interface Alert extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + AlertProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the Alert definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithVault, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of Alert definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a Alert definition. + */ + interface Blank extends WithVault { + } + + /** + * The stage of the alert definition allowing to specify Vault. + */ + interface WithVault { + /** + * Specifies . + * @return the next definition stage + */ + WithProperties withExistingVault(); + } + + /** + * The stage of the alert definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties The properties of a configure alert request + * @return the next definition stage + */ + WithCreate withProperties(ConfigureAlertRequestProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a Alert update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of Alert update stages. + */ + interface UpdateStages { + /** + * The stage of the alert update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties The properties of a configure alert request + * @return the next update stage + */ + Update withProperties(ConfigureAlertRequestProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AlertProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AlertProperties.java new file mode 100644 index 0000000000000..3a8298cd632ee --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AlertProperties.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The properties of an alert. + */ +public class AlertProperties { + /** + * A value indicating whether to send email to subscription administrator. + */ + @JsonProperty(value = "sendToOwners") + private String sendToOwners; + + /** + * The custom email address for sending emails. + */ + @JsonProperty(value = "customEmailAddresses") + private List customEmailAddresses; + + /** + * The locale for the email notification. + */ + @JsonProperty(value = "locale") + private String locale; + + /** + * Get a value indicating whether to send email to subscription administrator. + * + * @return the sendToOwners value + */ + public String sendToOwners() { + return this.sendToOwners; + } + + /** + * Set a value indicating whether to send email to subscription administrator. + * + * @param sendToOwners the sendToOwners value to set + * @return the AlertProperties object itself. + */ + public AlertProperties withSendToOwners(String sendToOwners) { + this.sendToOwners = sendToOwners; + return this; + } + + /** + * Get the custom email address for sending emails. + * + * @return the customEmailAddresses value + */ + public List customEmailAddresses() { + return this.customEmailAddresses; + } + + /** + * Set the custom email address for sending emails. + * + * @param customEmailAddresses the customEmailAddresses value to set + * @return the AlertProperties object itself. + */ + public AlertProperties withCustomEmailAddresses(List customEmailAddresses) { + this.customEmailAddresses = customEmailAddresses; + return this; + } + + /** + * Get the locale for the email notification. + * + * @return the locale value + */ + public String locale() { + return this.locale; + } + + /** + * Set the locale for the email notification. + * + * @param locale the locale value to set + * @return the AlertProperties object itself. + */ + public AlertProperties withLocale(String locale) { + this.locale = locale; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AlternateLocationRecoveryOption.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AlternateLocationRecoveryOption.java new file mode 100644 index 0000000000000..57cb1912c4112 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AlternateLocationRecoveryOption.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for AlternateLocationRecoveryOption. + */ +public final class AlternateLocationRecoveryOption extends ExpandableStringEnum { + /** Static value CreateVmIfNotFound for AlternateLocationRecoveryOption. */ + public static final AlternateLocationRecoveryOption CREATE_VM_IF_NOT_FOUND = fromString("CreateVmIfNotFound"); + + /** Static value NoAction for AlternateLocationRecoveryOption. */ + public static final AlternateLocationRecoveryOption NO_ACTION = fromString("NoAction"); + + /** + * Creates or finds a AlternateLocationRecoveryOption from its string representation. + * @param name a name to look for + * @return the corresponding AlternateLocationRecoveryOption + */ + @JsonCreator + public static AlternateLocationRecoveryOption fromString(String name) { + return fromString(name, AlternateLocationRecoveryOption.class); + } + + /** + * @return known AlternateLocationRecoveryOption values + */ + public static Collection values() { + return values(AlternateLocationRecoveryOption.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointInput.java new file mode 100644 index 0000000000000..115cff61f13a2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input to apply recovery point. + */ +public class ApplyRecoveryPointInput { + /** + * The input properties to apply recovery point. + */ + @JsonProperty(value = "properties") + private ApplyRecoveryPointInputProperties properties; + + /** + * Get the input properties to apply recovery point. + * + * @return the properties value + */ + public ApplyRecoveryPointInputProperties properties() { + return this.properties; + } + + /** + * Set the input properties to apply recovery point. + * + * @param properties the properties value to set + * @return the ApplyRecoveryPointInput object itself. + */ + public ApplyRecoveryPointInput withProperties(ApplyRecoveryPointInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointInputProperties.java new file mode 100644 index 0000000000000..52e37c3893a27 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointInputProperties.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input properties to apply recovery point. + */ +public class ApplyRecoveryPointInputProperties { + /** + * The recovery point Id. + */ + @JsonProperty(value = "recoveryPointId") + private String recoveryPointId; + + /** + * Provider specific input for applying recovery point. + */ + @JsonProperty(value = "providerSpecificDetails") + private ApplyRecoveryPointProviderSpecificInput providerSpecificDetails; + + /** + * Get the recovery point Id. + * + * @return the recoveryPointId value + */ + public String recoveryPointId() { + return this.recoveryPointId; + } + + /** + * Set the recovery point Id. + * + * @param recoveryPointId the recoveryPointId value to set + * @return the ApplyRecoveryPointInputProperties object itself. + */ + public ApplyRecoveryPointInputProperties withRecoveryPointId(String recoveryPointId) { + this.recoveryPointId = recoveryPointId; + return this; + } + + /** + * Get provider specific input for applying recovery point. + * + * @return the providerSpecificDetails value + */ + public ApplyRecoveryPointProviderSpecificInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set provider specific input for applying recovery point. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the ApplyRecoveryPointInputProperties object itself. + */ + public ApplyRecoveryPointInputProperties withProviderSpecificDetails(ApplyRecoveryPointProviderSpecificInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointProviderSpecificInput.java new file mode 100644 index 0000000000000..8bc28ab08b6fd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ApplyRecoveryPointProviderSpecificInput.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Provider specific input for apply recovery point. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ApplyRecoveryPointProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AApplyRecoveryPointInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzureApplyRecoveryPointInput.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2ApplyRecoveryPointInput.class) +}) +public class ApplyRecoveryPointProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AsrJobDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AsrJobDetails.java new file mode 100644 index 0000000000000..c0a2be27ac39e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AsrJobDetails.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents job details based on specific job type. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("AsrJobDetails") +public class AsrJobDetails extends JobDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AutomationRunbookTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AutomationRunbookTaskDetails.java new file mode 100644 index 0000000000000..b00be4504ab98 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AutomationRunbookTaskDetails.java @@ -0,0 +1,255 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the task details for an automation runbook. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("AutomationRunbookTaskDetails") +public class AutomationRunbookTaskDetails extends TaskTypeDetails { + /** + * The recovery plan task name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The cloud service of the automation runbook account. + */ + @JsonProperty(value = "cloudServiceName") + private String cloudServiceName; + + /** + * The subscription Id of the automation runbook account. + */ + @JsonProperty(value = "subscriptionId") + private String subscriptionId; + + /** + * The automation account name of the runbook. + */ + @JsonProperty(value = "accountName") + private String accountName; + + /** + * The runbook Id. + */ + @JsonProperty(value = "runbookId") + private String runbookId; + + /** + * The runbook name. + */ + @JsonProperty(value = "runbookName") + private String runbookName; + + /** + * The job Id of the runbook execution. + */ + @JsonProperty(value = "jobId") + private String jobId; + + /** + * The execution output of the runbook. + */ + @JsonProperty(value = "jobOutput") + private String jobOutput; + + /** + * A value indicating whether it is a primary side script or not. + */ + @JsonProperty(value = "isPrimarySideScript") + private Boolean isPrimarySideScript; + + /** + * Get the recovery plan task name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the recovery plan task name. + * + * @param name the name value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withName(String name) { + this.name = name; + return this; + } + + /** + * Get the cloud service of the automation runbook account. + * + * @return the cloudServiceName value + */ + public String cloudServiceName() { + return this.cloudServiceName; + } + + /** + * Set the cloud service of the automation runbook account. + * + * @param cloudServiceName the cloudServiceName value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withCloudServiceName(String cloudServiceName) { + this.cloudServiceName = cloudServiceName; + return this; + } + + /** + * Get the subscription Id of the automation runbook account. + * + * @return the subscriptionId value + */ + public String subscriptionId() { + return this.subscriptionId; + } + + /** + * Set the subscription Id of the automation runbook account. + * + * @param subscriptionId the subscriptionId value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /** + * Get the automation account name of the runbook. + * + * @return the accountName value + */ + public String accountName() { + return this.accountName; + } + + /** + * Set the automation account name of the runbook. + * + * @param accountName the accountName value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withAccountName(String accountName) { + this.accountName = accountName; + return this; + } + + /** + * Get the runbook Id. + * + * @return the runbookId value + */ + public String runbookId() { + return this.runbookId; + } + + /** + * Set the runbook Id. + * + * @param runbookId the runbookId value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withRunbookId(String runbookId) { + this.runbookId = runbookId; + return this; + } + + /** + * Get the runbook name. + * + * @return the runbookName value + */ + public String runbookName() { + return this.runbookName; + } + + /** + * Set the runbook name. + * + * @param runbookName the runbookName value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withRunbookName(String runbookName) { + this.runbookName = runbookName; + return this; + } + + /** + * Get the job Id of the runbook execution. + * + * @return the jobId value + */ + public String jobId() { + return this.jobId; + } + + /** + * Set the job Id of the runbook execution. + * + * @param jobId the jobId value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withJobId(String jobId) { + this.jobId = jobId; + return this; + } + + /** + * Get the execution output of the runbook. + * + * @return the jobOutput value + */ + public String jobOutput() { + return this.jobOutput; + } + + /** + * Set the execution output of the runbook. + * + * @param jobOutput the jobOutput value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withJobOutput(String jobOutput) { + this.jobOutput = jobOutput; + return this; + } + + /** + * Get a value indicating whether it is a primary side script or not. + * + * @return the isPrimarySideScript value + */ + public Boolean isPrimarySideScript() { + return this.isPrimarySideScript; + } + + /** + * Set a value indicating whether it is a primary side script or not. + * + * @param isPrimarySideScript the isPrimarySideScript value to set + * @return the AutomationRunbookTaskDetails object itself. + */ + public AutomationRunbookTaskDetails withIsPrimarySideScript(Boolean isPrimarySideScript) { + this.isPrimarySideScript = isPrimarySideScript; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureFabricCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureFabricCreationInput.java new file mode 100644 index 0000000000000..a5b6e11fb93df --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureFabricCreationInput.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Fabric provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("Azure") +public class AzureFabricCreationInput extends FabricSpecificCreationInput { + /** + * The Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set the Location. + * + * @param location the location value to set + * @return the AzureFabricCreationInput object itself. + */ + public AzureFabricCreationInput withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureFabricSpecificDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureFabricSpecificDetails.java new file mode 100644 index 0000000000000..5c90ae41ff7b5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureFabricSpecificDetails.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Azure Fabric Specific Details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("Azure") +public class AzureFabricSpecificDetails extends FabricSpecificDetails { + /** + * The Location for the Azure fabric. + */ + @JsonProperty(value = "location") + private String location; + + /** + * The container Ids for the Azure fabric. + */ + @JsonProperty(value = "containerIds") + private List containerIds; + + /** + * Get the Location for the Azure fabric. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set the Location for the Azure fabric. + * + * @param location the location value to set + * @return the AzureFabricSpecificDetails object itself. + */ + public AzureFabricSpecificDetails withLocation(String location) { + this.location = location; + return this; + } + + /** + * Get the container Ids for the Azure fabric. + * + * @return the containerIds value + */ + public List containerIds() { + return this.containerIds; + } + + /** + * Set the container Ids for the Azure fabric. + * + * @param containerIds the containerIds value to set + * @return the AzureFabricSpecificDetails object itself. + */ + public AzureFabricSpecificDetails withContainerIds(List containerIds) { + this.containerIds = containerIds; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureCreateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureCreateNetworkMappingInput.java new file mode 100644 index 0000000000000..1bfa9a4d25132 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureCreateNetworkMappingInput.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Create network mappings input properties/behavior specific to Azure to Azure + * Network mapping. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("AzureToAzure") +public class AzureToAzureCreateNetworkMappingInput extends FabricSpecificCreateNetworkMappingInput { + /** + * The primary azure vnet Id. + */ + @JsonProperty(value = "primaryNetworkId") + private String primaryNetworkId; + + /** + * Get the primary azure vnet Id. + * + * @return the primaryNetworkId value + */ + public String primaryNetworkId() { + return this.primaryNetworkId; + } + + /** + * Set the primary azure vnet Id. + * + * @param primaryNetworkId the primaryNetworkId value to set + * @return the AzureToAzureCreateNetworkMappingInput object itself. + */ + public AzureToAzureCreateNetworkMappingInput withPrimaryNetworkId(String primaryNetworkId) { + this.primaryNetworkId = primaryNetworkId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureNetworkMappingSettings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureNetworkMappingSettings.java new file mode 100644 index 0000000000000..c135d7c5c53df --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureNetworkMappingSettings.java @@ -0,0 +1,73 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * A2A Network Mapping fabric specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("AzureToAzure") +public class AzureToAzureNetworkMappingSettings extends NetworkMappingFabricSpecificSettings { + /** + * The primary fabric location. + */ + @JsonProperty(value = "primaryFabricLocation") + private String primaryFabricLocation; + + /** + * The recovery fabric location. + */ + @JsonProperty(value = "recoveryFabricLocation") + private String recoveryFabricLocation; + + /** + * Get the primary fabric location. + * + * @return the primaryFabricLocation value + */ + public String primaryFabricLocation() { + return this.primaryFabricLocation; + } + + /** + * Set the primary fabric location. + * + * @param primaryFabricLocation the primaryFabricLocation value to set + * @return the AzureToAzureNetworkMappingSettings object itself. + */ + public AzureToAzureNetworkMappingSettings withPrimaryFabricLocation(String primaryFabricLocation) { + this.primaryFabricLocation = primaryFabricLocation; + return this; + } + + /** + * Get the recovery fabric location. + * + * @return the recoveryFabricLocation value + */ + public String recoveryFabricLocation() { + return this.recoveryFabricLocation; + } + + /** + * Set the recovery fabric location. + * + * @param recoveryFabricLocation the recoveryFabricLocation value to set + * @return the AzureToAzureNetworkMappingSettings object itself. + */ + public AzureToAzureNetworkMappingSettings withRecoveryFabricLocation(String recoveryFabricLocation) { + this.recoveryFabricLocation = recoveryFabricLocation; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureUpdateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureUpdateNetworkMappingInput.java new file mode 100644 index 0000000000000..aac96435edfa0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureUpdateNetworkMappingInput.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Updates network mappings input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("AzureToAzure") +public class AzureToAzureUpdateNetworkMappingInput extends FabricSpecificUpdateNetworkMappingInput { + /** + * The primary azure vnet Id. + */ + @JsonProperty(value = "primaryNetworkId") + private String primaryNetworkId; + + /** + * Get the primary azure vnet Id. + * + * @return the primaryNetworkId value + */ + public String primaryNetworkId() { + return this.primaryNetworkId; + } + + /** + * Set the primary azure vnet Id. + * + * @param primaryNetworkId the primaryNetworkId value to set + * @return the AzureToAzureUpdateNetworkMappingInput object itself. + */ + public AzureToAzureUpdateNetworkMappingInput withPrimaryNetworkId(String primaryNetworkId) { + this.primaryNetworkId = primaryNetworkId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureVmSyncedConfigDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureVmSyncedConfigDetails.java new file mode 100644 index 0000000000000..171840bedf4e6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureToAzureVmSyncedConfigDetails.java @@ -0,0 +1,97 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Map; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Azure to Azure VM synced configuration details. + */ +public class AzureToAzureVmSyncedConfigDetails { + /** + * The Azure VM tags. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * The Azure role assignments. + */ + @JsonProperty(value = "roleAssignments") + private List roleAssignments; + + /** + * The Azure VM input endpoints. + */ + @JsonProperty(value = "inputEndpoints") + private List inputEndpoints; + + /** + * Get the Azure VM tags. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set the Azure VM tags. + * + * @param tags the tags value to set + * @return the AzureToAzureVmSyncedConfigDetails object itself. + */ + public AzureToAzureVmSyncedConfigDetails withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the Azure role assignments. + * + * @return the roleAssignments value + */ + public List roleAssignments() { + return this.roleAssignments; + } + + /** + * Set the Azure role assignments. + * + * @param roleAssignments the roleAssignments value to set + * @return the AzureToAzureVmSyncedConfigDetails object itself. + */ + public AzureToAzureVmSyncedConfigDetails withRoleAssignments(List roleAssignments) { + this.roleAssignments = roleAssignments; + return this; + } + + /** + * Get the Azure VM input endpoints. + * + * @return the inputEndpoints value + */ + public List inputEndpoints() { + return this.inputEndpoints; + } + + /** + * Set the Azure VM input endpoints. + * + * @param inputEndpoints the inputEndpoints value to set + * @return the AzureToAzureVmSyncedConfigDetails object itself. + */ + public AzureToAzureVmSyncedConfigDetails withInputEndpoints(List inputEndpoints) { + this.inputEndpoints = inputEndpoints; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureVmDiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureVmDiskDetails.java new file mode 100644 index 0000000000000..a9bcacd4396f7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/AzureVmDiskDetails.java @@ -0,0 +1,199 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Disk details for E2A provider. + */ +public class AzureVmDiskDetails { + /** + * VHD type. + */ + @JsonProperty(value = "vhdType") + private String vhdType; + + /** + * The VHD id. + */ + @JsonProperty(value = "vhdId") + private String vhdId; + + /** + * VHD name. + */ + @JsonProperty(value = "vhdName") + private String vhdName; + + /** + * Max side in MB. + */ + @JsonProperty(value = "maxSizeMB") + private String maxSizeMB; + + /** + * Blob uri of the Azure disk. + */ + @JsonProperty(value = "targetDiskLocation") + private String targetDiskLocation; + + /** + * The target Azure disk name. + */ + @JsonProperty(value = "targetDiskName") + private String targetDiskName; + + /** + * Ordinal\LunId of the disk for the Azure VM. + */ + @JsonProperty(value = "lunId") + private String lunId; + + /** + * Get vHD type. + * + * @return the vhdType value + */ + public String vhdType() { + return this.vhdType; + } + + /** + * Set vHD type. + * + * @param vhdType the vhdType value to set + * @return the AzureVmDiskDetails object itself. + */ + public AzureVmDiskDetails withVhdType(String vhdType) { + this.vhdType = vhdType; + return this; + } + + /** + * Get the VHD id. + * + * @return the vhdId value + */ + public String vhdId() { + return this.vhdId; + } + + /** + * Set the VHD id. + * + * @param vhdId the vhdId value to set + * @return the AzureVmDiskDetails object itself. + */ + public AzureVmDiskDetails withVhdId(String vhdId) { + this.vhdId = vhdId; + return this; + } + + /** + * Get vHD name. + * + * @return the vhdName value + */ + public String vhdName() { + return this.vhdName; + } + + /** + * Set vHD name. + * + * @param vhdName the vhdName value to set + * @return the AzureVmDiskDetails object itself. + */ + public AzureVmDiskDetails withVhdName(String vhdName) { + this.vhdName = vhdName; + return this; + } + + /** + * Get max side in MB. + * + * @return the maxSizeMB value + */ + public String maxSizeMB() { + return this.maxSizeMB; + } + + /** + * Set max side in MB. + * + * @param maxSizeMB the maxSizeMB value to set + * @return the AzureVmDiskDetails object itself. + */ + public AzureVmDiskDetails withMaxSizeMB(String maxSizeMB) { + this.maxSizeMB = maxSizeMB; + return this; + } + + /** + * Get blob uri of the Azure disk. + * + * @return the targetDiskLocation value + */ + public String targetDiskLocation() { + return this.targetDiskLocation; + } + + /** + * Set blob uri of the Azure disk. + * + * @param targetDiskLocation the targetDiskLocation value to set + * @return the AzureVmDiskDetails object itself. + */ + public AzureVmDiskDetails withTargetDiskLocation(String targetDiskLocation) { + this.targetDiskLocation = targetDiskLocation; + return this; + } + + /** + * Get the target Azure disk name. + * + * @return the targetDiskName value + */ + public String targetDiskName() { + return this.targetDiskName; + } + + /** + * Set the target Azure disk name. + * + * @param targetDiskName the targetDiskName value to set + * @return the AzureVmDiskDetails object itself. + */ + public AzureVmDiskDetails withTargetDiskName(String targetDiskName) { + this.targetDiskName = targetDiskName; + return this; + } + + /** + * Get ordinal\LunId of the disk for the Azure VM. + * + * @return the lunId value + */ + public String lunId() { + return this.lunId; + } + + /** + * Set ordinal\LunId of the disk for the Azure VM. + * + * @param lunId the lunId value to set + * @return the AzureVmDiskDetails object itself. + */ + public AzureVmDiskDetails withLunId(String lunId) { + this.lunId = lunId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ComputeSizeErrorDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ComputeSizeErrorDetails.java new file mode 100644 index 0000000000000..4004f14a340ee --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ComputeSizeErrorDetails.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents the error used to indicate why the target compute size is not + * applicable. + */ +public class ComputeSizeErrorDetails { + /** + * The error message. + */ + @JsonProperty(value = "message") + private String message; + + /** + * The severity of the error. + */ + @JsonProperty(value = "severity") + private String severity; + + /** + * Get the error message. + * + * @return the message value + */ + public String message() { + return this.message; + } + + /** + * Set the error message. + * + * @param message the message value to set + * @return the ComputeSizeErrorDetails object itself. + */ + public ComputeSizeErrorDetails withMessage(String message) { + this.message = message; + return this; + } + + /** + * Get the severity of the error. + * + * @return the severity value + */ + public String severity() { + return this.severity; + } + + /** + * Set the severity of the error. + * + * @param severity the severity value to set + * @return the ComputeSizeErrorDetails object itself. + */ + public ComputeSizeErrorDetails withSeverity(String severity) { + this.severity = severity; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigurationSettings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigurationSettings.java new file mode 100644 index 0000000000000..a659422825b4c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigurationSettings.java @@ -0,0 +1,27 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Replication provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ConfigurationSettings") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "HyperVVirtualMachine", value = HyperVVirtualMachineDetails.class), + @JsonSubTypes.Type(name = "ReplicationGroupDetails", value = ReplicationGroupDetails.class), + @JsonSubTypes.Type(name = "VmmVirtualMachine", value = VmmVirtualMachineDetails.class), + @JsonSubTypes.Type(name = "VMwareVirtualMachine", value = VMwareVirtualMachineDetails.class) +}) +public class ConfigurationSettings { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigureAlertRequest.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigureAlertRequest.java new file mode 100644 index 0000000000000..4240ac41ce64c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigureAlertRequest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Request to configure alerts for the system. + */ +public class ConfigureAlertRequest { + /** + * The properties of a configure alert request. + */ + @JsonProperty(value = "properties") + private ConfigureAlertRequestProperties properties; + + /** + * Get the properties of a configure alert request. + * + * @return the properties value + */ + public ConfigureAlertRequestProperties properties() { + return this.properties; + } + + /** + * Set the properties of a configure alert request. + * + * @param properties the properties value to set + * @return the ConfigureAlertRequest object itself. + */ + public ConfigureAlertRequest withProperties(ConfigureAlertRequestProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigureAlertRequestProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigureAlertRequestProperties.java new file mode 100644 index 0000000000000..978826ca3a524 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConfigureAlertRequestProperties.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Properties of a configure alert request. + */ +public class ConfigureAlertRequestProperties { + /** + * A value indicating whether to send email to subscription administrator. + */ + @JsonProperty(value = "sendToOwners") + private String sendToOwners; + + /** + * The custom email address for sending emails. + */ + @JsonProperty(value = "customEmailAddresses") + private List customEmailAddresses; + + /** + * The locale for the email notification. + */ + @JsonProperty(value = "locale") + private String locale; + + /** + * Get a value indicating whether to send email to subscription administrator. + * + * @return the sendToOwners value + */ + public String sendToOwners() { + return this.sendToOwners; + } + + /** + * Set a value indicating whether to send email to subscription administrator. + * + * @param sendToOwners the sendToOwners value to set + * @return the ConfigureAlertRequestProperties object itself. + */ + public ConfigureAlertRequestProperties withSendToOwners(String sendToOwners) { + this.sendToOwners = sendToOwners; + return this; + } + + /** + * Get the custom email address for sending emails. + * + * @return the customEmailAddresses value + */ + public List customEmailAddresses() { + return this.customEmailAddresses; + } + + /** + * Set the custom email address for sending emails. + * + * @param customEmailAddresses the customEmailAddresses value to set + * @return the ConfigureAlertRequestProperties object itself. + */ + public ConfigureAlertRequestProperties withCustomEmailAddresses(List customEmailAddresses) { + this.customEmailAddresses = customEmailAddresses; + return this; + } + + /** + * Get the locale for the email notification. + * + * @return the locale value + */ + public String locale() { + return this.locale; + } + + /** + * Set the locale for the email notification. + * + * @param locale the locale value to set + * @return the ConfigureAlertRequestProperties object itself. + */ + public ConfigureAlertRequestProperties withLocale(String locale) { + this.locale = locale; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConsistencyCheckTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConsistencyCheckTaskDetails.java new file mode 100644 index 0000000000000..1a35131a5668e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ConsistencyCheckTaskDetails.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class contains monitoring details of all the inconsistent Protected + * Entities in Vmm. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ConsistencyCheckTaskDetails") +public class ConsistencyCheckTaskDetails extends TaskTypeDetails { + /** + * The list of inconsistent Vm details. + */ + @JsonProperty(value = "vmDetails") + private List vmDetails; + + /** + * Get the list of inconsistent Vm details. + * + * @return the vmDetails value + */ + public List vmDetails() { + return this.vmDetails; + } + + /** + * Set the list of inconsistent Vm details. + * + * @param vmDetails the vmDetails value to set + * @return the ConsistencyCheckTaskDetails object itself. + */ + public ConsistencyCheckTaskDetails withVmDetails(List vmDetails) { + this.vmDetails = vmDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateNetworkMappingInput.java new file mode 100644 index 0000000000000..e7be2be163b26 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateNetworkMappingInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Create network mappings input. + */ +public class CreateNetworkMappingInput { + /** + * Input properties for creating network mapping. + */ + @JsonProperty(value = "properties") + private CreateNetworkMappingInputProperties properties; + + /** + * Get input properties for creating network mapping. + * + * @return the properties value + */ + public CreateNetworkMappingInputProperties properties() { + return this.properties; + } + + /** + * Set input properties for creating network mapping. + * + * @param properties the properties value to set + * @return the CreateNetworkMappingInput object itself. + */ + public CreateNetworkMappingInput withProperties(CreateNetworkMappingInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateNetworkMappingInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateNetworkMappingInputProperties.java new file mode 100644 index 0000000000000..359b2a2ad5242 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateNetworkMappingInputProperties.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Common input details for network mapping operation. + */ +public class CreateNetworkMappingInputProperties { + /** + * Recovery fabric Name. + */ + @JsonProperty(value = "recoveryFabricName") + private String recoveryFabricName; + + /** + * Recovery network Id. + */ + @JsonProperty(value = "recoveryNetworkId") + private String recoveryNetworkId; + + /** + * Fabric specific input properties. + */ + @JsonProperty(value = "fabricSpecificDetails") + private FabricSpecificCreateNetworkMappingInput fabricSpecificDetails; + + /** + * Get recovery fabric Name. + * + * @return the recoveryFabricName value + */ + public String recoveryFabricName() { + return this.recoveryFabricName; + } + + /** + * Set recovery fabric Name. + * + * @param recoveryFabricName the recoveryFabricName value to set + * @return the CreateNetworkMappingInputProperties object itself. + */ + public CreateNetworkMappingInputProperties withRecoveryFabricName(String recoveryFabricName) { + this.recoveryFabricName = recoveryFabricName; + return this; + } + + /** + * Get recovery network Id. + * + * @return the recoveryNetworkId value + */ + public String recoveryNetworkId() { + return this.recoveryNetworkId; + } + + /** + * Set recovery network Id. + * + * @param recoveryNetworkId the recoveryNetworkId value to set + * @return the CreateNetworkMappingInputProperties object itself. + */ + public CreateNetworkMappingInputProperties withRecoveryNetworkId(String recoveryNetworkId) { + this.recoveryNetworkId = recoveryNetworkId; + return this; + } + + /** + * Get fabric specific input properties. + * + * @return the fabricSpecificDetails value + */ + public FabricSpecificCreateNetworkMappingInput fabricSpecificDetails() { + return this.fabricSpecificDetails; + } + + /** + * Set fabric specific input properties. + * + * @param fabricSpecificDetails the fabricSpecificDetails value to set + * @return the CreateNetworkMappingInputProperties object itself. + */ + public CreateNetworkMappingInputProperties withFabricSpecificDetails(FabricSpecificCreateNetworkMappingInput fabricSpecificDetails) { + this.fabricSpecificDetails = fabricSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreatePolicyInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreatePolicyInput.java new file mode 100644 index 0000000000000..645cdcbd8c812 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreatePolicyInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Protection Policy input. + */ +public class CreatePolicyInput { + /** + * Policy creation properties. + */ + @JsonProperty(value = "properties") + private CreatePolicyInputProperties properties; + + /** + * Get policy creation properties. + * + * @return the properties value + */ + public CreatePolicyInputProperties properties() { + return this.properties; + } + + /** + * Set policy creation properties. + * + * @param properties the properties value to set + * @return the CreatePolicyInput object itself. + */ + public CreatePolicyInput withProperties(CreatePolicyInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreatePolicyInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreatePolicyInputProperties.java new file mode 100644 index 0000000000000..e9c927741f300 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreatePolicyInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy creation properties. + */ +public class CreatePolicyInputProperties { + /** + * The ReplicationProviderSettings. + */ + @JsonProperty(value = "providerSpecificInput") + private PolicyProviderSpecificInput providerSpecificInput; + + /** + * Get the ReplicationProviderSettings. + * + * @return the providerSpecificInput value + */ + public PolicyProviderSpecificInput providerSpecificInput() { + return this.providerSpecificInput; + } + + /** + * Set the ReplicationProviderSettings. + * + * @param providerSpecificInput the providerSpecificInput value to set + * @return the CreatePolicyInputProperties object itself. + */ + public CreatePolicyInputProperties withProviderSpecificInput(PolicyProviderSpecificInput providerSpecificInput) { + this.providerSpecificInput = providerSpecificInput; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerInput.java new file mode 100644 index 0000000000000..1e545e4a10440 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Create protection container input. + */ +public class CreateProtectionContainerInput { + /** + * Create protection container input properties. + */ + @JsonProperty(value = "properties") + private CreateProtectionContainerInputProperties properties; + + /** + * Get create protection container input properties. + * + * @return the properties value + */ + public CreateProtectionContainerInputProperties properties() { + return this.properties; + } + + /** + * Set create protection container input properties. + * + * @param properties the properties value to set + * @return the CreateProtectionContainerInput object itself. + */ + public CreateProtectionContainerInput withProperties(CreateProtectionContainerInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerInputProperties.java new file mode 100644 index 0000000000000..a7a6024f03d28 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerInputProperties.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Create protection container input properties. + */ +public class CreateProtectionContainerInputProperties { + /** + * Provider specific inputs for container creation. + */ + @JsonProperty(value = "providerSpecificInput") + private List providerSpecificInput; + + /** + * Get provider specific inputs for container creation. + * + * @return the providerSpecificInput value + */ + public List providerSpecificInput() { + return this.providerSpecificInput; + } + + /** + * Set provider specific inputs for container creation. + * + * @param providerSpecificInput the providerSpecificInput value to set + * @return the CreateProtectionContainerInputProperties object itself. + */ + public CreateProtectionContainerInputProperties withProviderSpecificInput(List providerSpecificInput) { + this.providerSpecificInput = providerSpecificInput; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerMappingInput.java new file mode 100644 index 0000000000000..ad4f9ad412628 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerMappingInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Configure pairing input. + */ +public class CreateProtectionContainerMappingInput { + /** + * Configure protection input properties. + */ + @JsonProperty(value = "properties") + private CreateProtectionContainerMappingInputProperties properties; + + /** + * Get configure protection input properties. + * + * @return the properties value + */ + public CreateProtectionContainerMappingInputProperties properties() { + return this.properties; + } + + /** + * Set configure protection input properties. + * + * @param properties the properties value to set + * @return the CreateProtectionContainerMappingInput object itself. + */ + public CreateProtectionContainerMappingInput withProperties(CreateProtectionContainerMappingInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerMappingInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerMappingInputProperties.java new file mode 100644 index 0000000000000..71054881d0299 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateProtectionContainerMappingInputProperties.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Configure pairing input properties. + */ +public class CreateProtectionContainerMappingInputProperties { + /** + * The target unique protection container name. + */ + @JsonProperty(value = "targetProtectionContainerId") + private String targetProtectionContainerId; + + /** + * Applicable policy. + */ + @JsonProperty(value = "policyId") + private String policyId; + + /** + * Provider specific input for pairing. + */ + @JsonProperty(value = "providerSpecificInput") + private ReplicationProviderSpecificContainerMappingInput providerSpecificInput; + + /** + * Get the target unique protection container name. + * + * @return the targetProtectionContainerId value + */ + public String targetProtectionContainerId() { + return this.targetProtectionContainerId; + } + + /** + * Set the target unique protection container name. + * + * @param targetProtectionContainerId the targetProtectionContainerId value to set + * @return the CreateProtectionContainerMappingInputProperties object itself. + */ + public CreateProtectionContainerMappingInputProperties withTargetProtectionContainerId(String targetProtectionContainerId) { + this.targetProtectionContainerId = targetProtectionContainerId; + return this; + } + + /** + * Get applicable policy. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Set applicable policy. + * + * @param policyId the policyId value to set + * @return the CreateProtectionContainerMappingInputProperties object itself. + */ + public CreateProtectionContainerMappingInputProperties withPolicyId(String policyId) { + this.policyId = policyId; + return this; + } + + /** + * Get provider specific input for pairing. + * + * @return the providerSpecificInput value + */ + public ReplicationProviderSpecificContainerMappingInput providerSpecificInput() { + return this.providerSpecificInput; + } + + /** + * Set provider specific input for pairing. + * + * @param providerSpecificInput the providerSpecificInput value to set + * @return the CreateProtectionContainerMappingInputProperties object itself. + */ + public CreateProtectionContainerMappingInputProperties withProviderSpecificInput(ReplicationProviderSpecificContainerMappingInput providerSpecificInput) { + this.providerSpecificInput = providerSpecificInput; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateRecoveryPlanInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateRecoveryPlanInput.java new file mode 100644 index 0000000000000..5756fff8dd1f6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateRecoveryPlanInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Create recovery plan input class. + */ +public class CreateRecoveryPlanInput { + /** + * Recovery plan creation properties. + */ + @JsonProperty(value = "properties", required = true) + private CreateRecoveryPlanInputProperties properties; + + /** + * Get recovery plan creation properties. + * + * @return the properties value + */ + public CreateRecoveryPlanInputProperties properties() { + return this.properties; + } + + /** + * Set recovery plan creation properties. + * + * @param properties the properties value to set + * @return the CreateRecoveryPlanInput object itself. + */ + public CreateRecoveryPlanInput withProperties(CreateRecoveryPlanInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateRecoveryPlanInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateRecoveryPlanInputProperties.java new file mode 100644 index 0000000000000..1f6e4b7816e9d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CreateRecoveryPlanInputProperties.java @@ -0,0 +1,123 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan creation properties. + */ +public class CreateRecoveryPlanInputProperties { + /** + * The primary fabric Id. + */ + @JsonProperty(value = "primaryFabricId", required = true) + private String primaryFabricId; + + /** + * The recovery fabric Id. + */ + @JsonProperty(value = "recoveryFabricId", required = true) + private String recoveryFabricId; + + /** + * The failover deployment model. Possible values include: 'NotApplicable', + * 'Classic', 'ResourceManager'. + */ + @JsonProperty(value = "failoverDeploymentModel") + private FailoverDeploymentModel failoverDeploymentModel; + + /** + * The recovery plan groups. + */ + @JsonProperty(value = "groups", required = true) + private List groups; + + /** + * Get the primary fabric Id. + * + * @return the primaryFabricId value + */ + public String primaryFabricId() { + return this.primaryFabricId; + } + + /** + * Set the primary fabric Id. + * + * @param primaryFabricId the primaryFabricId value to set + * @return the CreateRecoveryPlanInputProperties object itself. + */ + public CreateRecoveryPlanInputProperties withPrimaryFabricId(String primaryFabricId) { + this.primaryFabricId = primaryFabricId; + return this; + } + + /** + * Get the recovery fabric Id. + * + * @return the recoveryFabricId value + */ + public String recoveryFabricId() { + return this.recoveryFabricId; + } + + /** + * Set the recovery fabric Id. + * + * @param recoveryFabricId the recoveryFabricId value to set + * @return the CreateRecoveryPlanInputProperties object itself. + */ + public CreateRecoveryPlanInputProperties withRecoveryFabricId(String recoveryFabricId) { + this.recoveryFabricId = recoveryFabricId; + return this; + } + + /** + * Get the failover deployment model. Possible values include: 'NotApplicable', 'Classic', 'ResourceManager'. + * + * @return the failoverDeploymentModel value + */ + public FailoverDeploymentModel failoverDeploymentModel() { + return this.failoverDeploymentModel; + } + + /** + * Set the failover deployment model. Possible values include: 'NotApplicable', 'Classic', 'ResourceManager'. + * + * @param failoverDeploymentModel the failoverDeploymentModel value to set + * @return the CreateRecoveryPlanInputProperties object itself. + */ + public CreateRecoveryPlanInputProperties withFailoverDeploymentModel(FailoverDeploymentModel failoverDeploymentModel) { + this.failoverDeploymentModel = failoverDeploymentModel; + return this; + } + + /** + * Get the recovery plan groups. + * + * @return the groups value + */ + public List groups() { + return this.groups; + } + + /** + * Set the recovery plan groups. + * + * @param groups the groups value to set + * @return the CreateRecoveryPlanInputProperties object itself. + */ + public CreateRecoveryPlanInputProperties withGroups(List groups) { + this.groups = groups; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CurrentJobDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CurrentJobDetails.java new file mode 100644 index 0000000000000..156c4dacf2928 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CurrentJobDetails.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Current job details of the migration item. + */ +public class CurrentJobDetails { + /** + * The job name. + */ + @JsonProperty(value = "jobName") + private String jobName; + + /** + * The ARM Id of the job being executed. + */ + @JsonProperty(value = "jobId") + private String jobId; + + /** + * The start time of the job. + */ + @JsonProperty(value = "startTime") + private DateTime startTime; + + /** + * Get the job name. + * + * @return the jobName value + */ + public String jobName() { + return this.jobName; + } + + /** + * Set the job name. + * + * @param jobName the jobName value to set + * @return the CurrentJobDetails object itself. + */ + public CurrentJobDetails withJobName(String jobName) { + this.jobName = jobName; + return this; + } + + /** + * Get the ARM Id of the job being executed. + * + * @return the jobId value + */ + public String jobId() { + return this.jobId; + } + + /** + * Set the ARM Id of the job being executed. + * + * @param jobId the jobId value to set + * @return the CurrentJobDetails object itself. + */ + public CurrentJobDetails withJobId(String jobId) { + this.jobId = jobId; + return this; + } + + /** + * Get the start time of the job. + * + * @return the startTime value + */ + public DateTime startTime() { + return this.startTime; + } + + /** + * Set the start time of the job. + * + * @param startTime the startTime value to set + * @return the CurrentJobDetails object itself. + */ + public CurrentJobDetails withStartTime(DateTime startTime) { + this.startTime = startTime; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CurrentScenarioDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CurrentScenarioDetails.java new file mode 100644 index 0000000000000..6ad4ad82c9286 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/CurrentScenarioDetails.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Current scenario details of the protected entity. + */ +public class CurrentScenarioDetails { + /** + * Scenario name. + */ + @JsonProperty(value = "scenarioName") + private String scenarioName; + + /** + * ARM Id of the job being executed. + */ + @JsonProperty(value = "jobId") + private String jobId; + + /** + * Start time of the workflow. + */ + @JsonProperty(value = "startTime") + private DateTime startTime; + + /** + * Get scenario name. + * + * @return the scenarioName value + */ + public String scenarioName() { + return this.scenarioName; + } + + /** + * Set scenario name. + * + * @param scenarioName the scenarioName value to set + * @return the CurrentScenarioDetails object itself. + */ + public CurrentScenarioDetails withScenarioName(String scenarioName) { + this.scenarioName = scenarioName; + return this; + } + + /** + * Get aRM Id of the job being executed. + * + * @return the jobId value + */ + public String jobId() { + return this.jobId; + } + + /** + * Set aRM Id of the job being executed. + * + * @param jobId the jobId value to set + * @return the CurrentScenarioDetails object itself. + */ + public CurrentScenarioDetails withJobId(String jobId) { + this.jobId = jobId; + return this; + } + + /** + * Get start time of the workflow. + * + * @return the startTime value + */ + public DateTime startTime() { + return this.startTime; + } + + /** + * Set start time of the workflow. + * + * @param startTime the startTime value to set + * @return the CurrentScenarioDetails object itself. + */ + public CurrentScenarioDetails withStartTime(DateTime startTime) { + this.startTime = startTime; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DataStore.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DataStore.java new file mode 100644 index 0000000000000..68c699c8f7e1f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DataStore.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The data store details of the MT. + */ +public class DataStore { + /** + * The symbolic name of data store. + */ + @JsonProperty(value = "symbolicName") + private String symbolicName; + + /** + * The uuid of data store. + */ + @JsonProperty(value = "uuid") + private String uuid; + + /** + * The capacity of data store in GBs. + */ + @JsonProperty(value = "capacity") + private String capacity; + + /** + * The free space of data store in GBs. + */ + @JsonProperty(value = "freeSpace") + private String freeSpace; + + /** + * The type of data store. + */ + @JsonProperty(value = "type") + private String type; + + /** + * Get the symbolic name of data store. + * + * @return the symbolicName value + */ + public String symbolicName() { + return this.symbolicName; + } + + /** + * Set the symbolic name of data store. + * + * @param symbolicName the symbolicName value to set + * @return the DataStore object itself. + */ + public DataStore withSymbolicName(String symbolicName) { + this.symbolicName = symbolicName; + return this; + } + + /** + * Get the uuid of data store. + * + * @return the uuid value + */ + public String uuid() { + return this.uuid; + } + + /** + * Set the uuid of data store. + * + * @param uuid the uuid value to set + * @return the DataStore object itself. + */ + public DataStore withUuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get the capacity of data store in GBs. + * + * @return the capacity value + */ + public String capacity() { + return this.capacity; + } + + /** + * Set the capacity of data store in GBs. + * + * @param capacity the capacity value to set + * @return the DataStore object itself. + */ + public DataStore withCapacity(String capacity) { + this.capacity = capacity; + return this; + } + + /** + * Get the free space of data store in GBs. + * + * @return the freeSpace value + */ + public String freeSpace() { + return this.freeSpace; + } + + /** + * Set the free space of data store in GBs. + * + * @param freeSpace the freeSpace value to set + * @return the DataStore object itself. + */ + public DataStore withFreeSpace(String freeSpace) { + this.freeSpace = freeSpace; + return this; + } + + /** + * Get the type of data store. + * + * @return the type value + */ + public String type() { + return this.type; + } + + /** + * Set the type of data store. + * + * @param type the type value to set + * @return the DataStore object itself. + */ + public DataStore withType(String type) { + this.type = type; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DataSyncStatus.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DataSyncStatus.java new file mode 100644 index 0000000000000..01b6106726899 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DataSyncStatus.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for DataSyncStatus. + */ +public final class DataSyncStatus extends ExpandableStringEnum { + /** Static value ForDownTime for DataSyncStatus. */ + public static final DataSyncStatus FOR_DOWN_TIME = fromString("ForDownTime"); + + /** Static value ForSynchronization for DataSyncStatus. */ + public static final DataSyncStatus FOR_SYNCHRONIZATION = fromString("ForSynchronization"); + + /** + * Creates or finds a DataSyncStatus from its string representation. + * @param name a name to look for + * @return the corresponding DataSyncStatus + */ + @JsonCreator + public static DataSyncStatus fromString(String name) { + return fromString(name, DataSyncStatus.class); + } + + /** + * @return known DataSyncStatus values + */ + public static Collection values() { + return values(DataSyncStatus.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionInput.java new file mode 100644 index 0000000000000..044192abe2725 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Disable protection input. + */ +public class DisableProtectionInput { + /** + * Disable protection input properties. + */ + @JsonProperty(value = "properties") + private DisableProtectionInputProperties properties; + + /** + * Get disable protection input properties. + * + * @return the properties value + */ + public DisableProtectionInputProperties properties() { + return this.properties; + } + + /** + * Set disable protection input properties. + * + * @param properties the properties value to set + * @return the DisableProtectionInput object itself. + */ + public DisableProtectionInput withProperties(DisableProtectionInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionInputProperties.java new file mode 100644 index 0000000000000..ffa6b832d65a5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionInputProperties.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Disable protection input properties. + */ +public class DisableProtectionInputProperties { + /** + * Disable protection reason. It can have values + * NotSpecified/MigrationComplete. Possible values include: 'NotSpecified', + * 'MigrationComplete'. + */ + @JsonProperty(value = "disableProtectionReason") + private DisableProtectionReason disableProtectionReason; + + /** + * Replication provider specific input. + */ + @JsonProperty(value = "replicationProviderInput") + private DisableProtectionProviderSpecificInput replicationProviderInput; + + /** + * Get disable protection reason. It can have values NotSpecified/MigrationComplete. Possible values include: 'NotSpecified', 'MigrationComplete'. + * + * @return the disableProtectionReason value + */ + public DisableProtectionReason disableProtectionReason() { + return this.disableProtectionReason; + } + + /** + * Set disable protection reason. It can have values NotSpecified/MigrationComplete. Possible values include: 'NotSpecified', 'MigrationComplete'. + * + * @param disableProtectionReason the disableProtectionReason value to set + * @return the DisableProtectionInputProperties object itself. + */ + public DisableProtectionInputProperties withDisableProtectionReason(DisableProtectionReason disableProtectionReason) { + this.disableProtectionReason = disableProtectionReason; + return this; + } + + /** + * Get replication provider specific input. + * + * @return the replicationProviderInput value + */ + public DisableProtectionProviderSpecificInput replicationProviderInput() { + return this.replicationProviderInput; + } + + /** + * Set replication provider specific input. + * + * @param replicationProviderInput the replicationProviderInput value to set + * @return the DisableProtectionInputProperties object itself. + */ + public DisableProtectionInputProperties withReplicationProviderInput(DisableProtectionProviderSpecificInput replicationProviderInput) { + this.replicationProviderInput = replicationProviderInput; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionProviderSpecificInput.java new file mode 100644 index 0000000000000..f711ade21b9ad --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionProviderSpecificInput.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Disable protection provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("DisableProtectionProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "InMage", value = InMageDisableProtectionProviderSpecificInput.class) +}) +public class DisableProtectionProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionReason.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionReason.java new file mode 100644 index 0000000000000..1b305235fc56e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DisableProtectionReason.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for DisableProtectionReason. + */ +public final class DisableProtectionReason extends ExpandableStringEnum { + /** Static value NotSpecified for DisableProtectionReason. */ + public static final DisableProtectionReason NOT_SPECIFIED = fromString("NotSpecified"); + + /** Static value MigrationComplete for DisableProtectionReason. */ + public static final DisableProtectionReason MIGRATION_COMPLETE = fromString("MigrationComplete"); + + /** + * Creates or finds a DisableProtectionReason from its string representation. + * @param name a name to look for + * @return the corresponding DisableProtectionReason + */ + @JsonCreator + public static DisableProtectionReason fromString(String name) { + return fromString(name, DisableProtectionReason.class); + } + + /** + * @return known DisableProtectionReason values + */ + public static Collection values() { + return values(DisableProtectionReason.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiscoverProtectableItemRequest.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiscoverProtectableItemRequest.java new file mode 100644 index 0000000000000..3ad952d53ac20 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiscoverProtectableItemRequest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Request to add a physical machine as a protectable item in a container. + */ +public class DiscoverProtectableItemRequest { + /** + * The properties of a discover protectable item request. + */ + @JsonProperty(value = "properties") + private DiscoverProtectableItemRequestProperties properties; + + /** + * Get the properties of a discover protectable item request. + * + * @return the properties value + */ + public DiscoverProtectableItemRequestProperties properties() { + return this.properties; + } + + /** + * Set the properties of a discover protectable item request. + * + * @param properties the properties value to set + * @return the DiscoverProtectableItemRequest object itself. + */ + public DiscoverProtectableItemRequest withProperties(DiscoverProtectableItemRequestProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiscoverProtectableItemRequestProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiscoverProtectableItemRequestProperties.java new file mode 100644 index 0000000000000..f4c3670667d03 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiscoverProtectableItemRequestProperties.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Discover protectable item properties. + */ +public class DiscoverProtectableItemRequestProperties { + /** + * The friendly name of the physical machine. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The IP address of the physical machine to be discovered. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The OS type on the physical machine. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * Get the friendly name of the physical machine. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the friendly name of the physical machine. + * + * @param friendlyName the friendlyName value to set + * @return the DiscoverProtectableItemRequestProperties object itself. + */ + public DiscoverProtectableItemRequestProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the IP address of the physical machine to be discovered. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the IP address of the physical machine to be discovered. + * + * @param ipAddress the ipAddress value to set + * @return the DiscoverProtectableItemRequestProperties object itself. + */ + public DiscoverProtectableItemRequestProperties withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the OS type on the physical machine. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the OS type on the physical machine. + * + * @param osType the osType value to set + * @return the DiscoverProtectableItemRequestProperties object itself. + */ + public DiscoverProtectableItemRequestProperties withOsType(String osType) { + this.osType = osType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskAccountType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskAccountType.java new file mode 100644 index 0000000000000..66aa62a33e921 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskAccountType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for DiskAccountType. + */ +public final class DiskAccountType extends ExpandableStringEnum { + /** Static value Standard_LRS for DiskAccountType. */ + public static final DiskAccountType STANDARD_LRS = fromString("Standard_LRS"); + + /** Static value Premium_LRS for DiskAccountType. */ + public static final DiskAccountType PREMIUM_LRS = fromString("Premium_LRS"); + + /** Static value StandardSSD_LRS for DiskAccountType. */ + public static final DiskAccountType STANDARD_SSD_LRS = fromString("StandardSSD_LRS"); + + /** + * Creates or finds a DiskAccountType from its string representation. + * @param name a name to look for + * @return the corresponding DiskAccountType + */ + @JsonCreator + public static DiskAccountType fromString(String name) { + return fromString(name, DiskAccountType.class); + } + + /** + * @return known DiskAccountType values + */ + public static Collection values() { + return values(DiskAccountType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskDetails.java new file mode 100644 index 0000000000000..26e86705a66d0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskDetails.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * On-prem disk details data. + */ +public class DiskDetails { + /** + * The hard disk max size in MB. + */ + @JsonProperty(value = "maxSizeMB") + private Long maxSizeMB; + + /** + * The type of the volume. + */ + @JsonProperty(value = "vhdType") + private String vhdType; + + /** + * The VHD Id. + */ + @JsonProperty(value = "vhdId") + private String vhdId; + + /** + * The VHD name. + */ + @JsonProperty(value = "vhdName") + private String vhdName; + + /** + * Get the hard disk max size in MB. + * + * @return the maxSizeMB value + */ + public Long maxSizeMB() { + return this.maxSizeMB; + } + + /** + * Set the hard disk max size in MB. + * + * @param maxSizeMB the maxSizeMB value to set + * @return the DiskDetails object itself. + */ + public DiskDetails withMaxSizeMB(Long maxSizeMB) { + this.maxSizeMB = maxSizeMB; + return this; + } + + /** + * Get the type of the volume. + * + * @return the vhdType value + */ + public String vhdType() { + return this.vhdType; + } + + /** + * Set the type of the volume. + * + * @param vhdType the vhdType value to set + * @return the DiskDetails object itself. + */ + public DiskDetails withVhdType(String vhdType) { + this.vhdType = vhdType; + return this; + } + + /** + * Get the VHD Id. + * + * @return the vhdId value + */ + public String vhdId() { + return this.vhdId; + } + + /** + * Set the VHD Id. + * + * @param vhdId the vhdId value to set + * @return the DiskDetails object itself. + */ + public DiskDetails withVhdId(String vhdId) { + this.vhdId = vhdId; + return this; + } + + /** + * Get the VHD name. + * + * @return the vhdName value + */ + public String vhdName() { + return this.vhdName; + } + + /** + * Set the VHD name. + * + * @param vhdName the vhdName value to set + * @return the DiskDetails object itself. + */ + public DiskDetails withVhdName(String vhdName) { + this.vhdName = vhdName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskEncryptionInfo.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskEncryptionInfo.java new file mode 100644 index 0000000000000..afcc68d8d0337 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskEncryptionInfo.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery disk encryption info (BEK and KEK). + */ +public class DiskEncryptionInfo { + /** + * The recovery KeyVault reference for secret. + */ + @JsonProperty(value = "diskEncryptionKeyInfo") + private DiskEncryptionKeyInfo diskEncryptionKeyInfo; + + /** + * The recovery KeyVault reference for key. + */ + @JsonProperty(value = "keyEncryptionKeyInfo") + private KeyEncryptionKeyInfo keyEncryptionKeyInfo; + + /** + * Get the recovery KeyVault reference for secret. + * + * @return the diskEncryptionKeyInfo value + */ + public DiskEncryptionKeyInfo diskEncryptionKeyInfo() { + return this.diskEncryptionKeyInfo; + } + + /** + * Set the recovery KeyVault reference for secret. + * + * @param diskEncryptionKeyInfo the diskEncryptionKeyInfo value to set + * @return the DiskEncryptionInfo object itself. + */ + public DiskEncryptionInfo withDiskEncryptionKeyInfo(DiskEncryptionKeyInfo diskEncryptionKeyInfo) { + this.diskEncryptionKeyInfo = diskEncryptionKeyInfo; + return this; + } + + /** + * Get the recovery KeyVault reference for key. + * + * @return the keyEncryptionKeyInfo value + */ + public KeyEncryptionKeyInfo keyEncryptionKeyInfo() { + return this.keyEncryptionKeyInfo; + } + + /** + * Set the recovery KeyVault reference for key. + * + * @param keyEncryptionKeyInfo the keyEncryptionKeyInfo value to set + * @return the DiskEncryptionInfo object itself. + */ + public DiskEncryptionInfo withKeyEncryptionKeyInfo(KeyEncryptionKeyInfo keyEncryptionKeyInfo) { + this.keyEncryptionKeyInfo = keyEncryptionKeyInfo; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskEncryptionKeyInfo.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskEncryptionKeyInfo.java new file mode 100644 index 0000000000000..73070281019d8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskEncryptionKeyInfo.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Disk Encryption Key Information (BitLocker Encryption Key (BEK) on Windows). + */ +public class DiskEncryptionKeyInfo { + /** + * The secret url / identifier. + */ + @JsonProperty(value = "secretIdentifier") + private String secretIdentifier; + + /** + * The KeyVault resource ARM id for secret. + */ + @JsonProperty(value = "keyVaultResourceArmId") + private String keyVaultResourceArmId; + + /** + * Get the secret url / identifier. + * + * @return the secretIdentifier value + */ + public String secretIdentifier() { + return this.secretIdentifier; + } + + /** + * Set the secret url / identifier. + * + * @param secretIdentifier the secretIdentifier value to set + * @return the DiskEncryptionKeyInfo object itself. + */ + public DiskEncryptionKeyInfo withSecretIdentifier(String secretIdentifier) { + this.secretIdentifier = secretIdentifier; + return this; + } + + /** + * Get the KeyVault resource ARM id for secret. + * + * @return the keyVaultResourceArmId value + */ + public String keyVaultResourceArmId() { + return this.keyVaultResourceArmId; + } + + /** + * Set the KeyVault resource ARM id for secret. + * + * @param keyVaultResourceArmId the keyVaultResourceArmId value to set + * @return the DiskEncryptionKeyInfo object itself. + */ + public DiskEncryptionKeyInfo withKeyVaultResourceArmId(String keyVaultResourceArmId) { + this.keyVaultResourceArmId = keyVaultResourceArmId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskType.java new file mode 100644 index 0000000000000..d75d14e034b39 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for DiskType. + */ +public final class DiskType extends ExpandableStringEnum { + /** Static value Standard_LRS for DiskType. */ + public static final DiskType STANDARD_LRS = fromString("Standard_LRS"); + + /** Static value Premium_LRS for DiskType. */ + public static final DiskType PREMIUM_LRS = fromString("Premium_LRS"); + + /** Static value StandardSSD_LRS for DiskType. */ + public static final DiskType STANDARD_SSD_LRS = fromString("StandardSSD_LRS"); + + /** + * Creates or finds a DiskType from its string representation. + * @param name a name to look for + * @return the corresponding DiskType + */ + @JsonCreator + public static DiskType fromString(String name) { + return fromString(name, DiskType.class); + } + + /** + * @return known DiskType values + */ + public static Collection values() { + return values(DiskType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskVolumeDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskVolumeDetails.java new file mode 100644 index 0000000000000..413cf38fe1a3a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/DiskVolumeDetails.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Volume details. + */ +public class DiskVolumeDetails { + /** + * The volume label. + */ + @JsonProperty(value = "label") + private String label; + + /** + * The volume name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Get the volume label. + * + * @return the label value + */ + public String label() { + return this.label; + } + + /** + * Set the volume label. + * + * @param label the label value to set + * @return the DiskVolumeDetails object itself. + */ + public DiskVolumeDetails withLabel(String label) { + this.label = label; + return this; + } + + /** + * Get the volume name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the volume name. + * + * @param name the name value to set + * @return the DiskVolumeDetails object itself. + */ + public DiskVolumeDetails withName(String name) { + this.name = name; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Display.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Display.java new file mode 100644 index 0000000000000..a590bf3e57231 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Display.java @@ -0,0 +1,144 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Contains the localized display information for this particular operation / + * action. These value will be used by several clients for (1) custom role + * definitions for RBAC; (2) complex query filters for the event service; and + * (3) audit history / records for management operations. + */ +public class Display { + /** + * The provider. The localized friendly form of the resource provider name + * – it is expected to also include the publisher/company responsible. It + * should use Title Casing and begin with "Microsoft" for 1st party + * services. e.g. "Microsoft Monitoring Insights" or "Microsoft Compute.". + */ + @JsonProperty(value = "provider") + private String provider; + + /** + * The resource. The localized friendly form of the resource related to + * this action/operation – it should match the public documentation for the + * resource provider. It should use Title Casing. This value should be + * unique for a particular URL type (e.g. nested types should *not* reuse + * their parent’s display.resource field). e.g. "Virtual Machines" or + * "Scheduler Job Collections", or "Virtual Machine VM Sizes" or "Scheduler + * Jobs". + */ + @JsonProperty(value = "resource") + private String resource; + + /** + * The operation. The localized friendly name for the operation, as it + * should be shown to the user. It should be concise (to fit in drop downs) + * but clear (i.e. self-documenting). It should use Title Casing. + * Prescriptive guidance: Read Create or Update Delete 'ActionName'. + */ + @JsonProperty(value = "operation") + private String operation; + + /** + * The description. The localized friendly description for the operation, + * as it should be shown to the user. It should be thorough, yet concise – + * it will be used in tool tips and detailed views. Prescriptive guidance + * for namespaces: Read any 'display.provider' resource Create or Update + * any 'display.provider' resource Delete any 'display.provider' resource + * Perform any other action on any 'display.provider' resource Prescriptive + * guidance for namespaces: Read any 'display.resource' Create or Update + * any 'display.resource' Delete any 'display.resource' 'ActionName' any + * 'display.resources'. + */ + @JsonProperty(value = "description") + private String description; + + /** + * Get the provider. The localized friendly form of the resource provider name – it is expected to also include the publisher/company responsible. It should use Title Casing and begin with "Microsoft" for 1st party services. e.g. "Microsoft Monitoring Insights" or "Microsoft Compute.". + * + * @return the provider value + */ + public String provider() { + return this.provider; + } + + /** + * Set the provider. The localized friendly form of the resource provider name – it is expected to also include the publisher/company responsible. It should use Title Casing and begin with "Microsoft" for 1st party services. e.g. "Microsoft Monitoring Insights" or "Microsoft Compute.". + * + * @param provider the provider value to set + * @return the Display object itself. + */ + public Display withProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get the resource. The localized friendly form of the resource related to this action/operation – it should match the public documentation for the resource provider. It should use Title Casing. This value should be unique for a particular URL type (e.g. nested types should *not* reuse their parent’s display.resource field). e.g. "Virtual Machines" or "Scheduler Job Collections", or "Virtual Machine VM Sizes" or "Scheduler Jobs". + * + * @return the resource value + */ + public String resource() { + return this.resource; + } + + /** + * Set the resource. The localized friendly form of the resource related to this action/operation – it should match the public documentation for the resource provider. It should use Title Casing. This value should be unique for a particular URL type (e.g. nested types should *not* reuse their parent’s display.resource field). e.g. "Virtual Machines" or "Scheduler Job Collections", or "Virtual Machine VM Sizes" or "Scheduler Jobs". + * + * @param resource the resource value to set + * @return the Display object itself. + */ + public Display withResource(String resource) { + this.resource = resource; + return this; + } + + /** + * Get the operation. The localized friendly name for the operation, as it should be shown to the user. It should be concise (to fit in drop downs) but clear (i.e. self-documenting). It should use Title Casing. Prescriptive guidance: Read Create or Update Delete 'ActionName'. + * + * @return the operation value + */ + public String operation() { + return this.operation; + } + + /** + * Set the operation. The localized friendly name for the operation, as it should be shown to the user. It should be concise (to fit in drop downs) but clear (i.e. self-documenting). It should use Title Casing. Prescriptive guidance: Read Create or Update Delete 'ActionName'. + * + * @param operation the operation value to set + * @return the Display object itself. + */ + public Display withOperation(String operation) { + this.operation = operation; + return this; + } + + /** + * Get the description. The localized friendly description for the operation, as it should be shown to the user. It should be thorough, yet concise – it will be used in tool tips and detailed views. Prescriptive guidance for namespaces: Read any 'display.provider' resource Create or Update any 'display.provider' resource Delete any 'display.provider' resource Perform any other action on any 'display.provider' resource Prescriptive guidance for namespaces: Read any 'display.resource' Create or Update any 'display.resource' Delete any 'display.resource' 'ActionName' any 'display.resources'. + * + * @return the description value + */ + public String description() { + return this.description; + } + + /** + * Set the description. The localized friendly description for the operation, as it should be shown to the user. It should be thorough, yet concise – it will be used in tool tips and detailed views. Prescriptive guidance for namespaces: Read any 'display.provider' resource Create or Update any 'display.provider' resource Delete any 'display.provider' resource Perform any other action on any 'display.provider' resource Prescriptive guidance for namespaces: Read any 'display.resource' Create or Update any 'display.resource' Delete any 'display.resource' 'ActionName' any 'display.resources'. + * + * @param description the description value to set + * @return the Display object itself. + */ + public Display withDescription(String description) { + this.description = description; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationInput.java new file mode 100644 index 0000000000000..7c008e59bfe10 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Enable migration input. + */ +public class EnableMigrationInput { + /** + * Enable migration input properties. + */ + @JsonProperty(value = "properties", required = true) + private EnableMigrationInputProperties properties; + + /** + * Get enable migration input properties. + * + * @return the properties value + */ + public EnableMigrationInputProperties properties() { + return this.properties; + } + + /** + * Set enable migration input properties. + * + * @param properties the properties value to set + * @return the EnableMigrationInput object itself. + */ + public EnableMigrationInput withProperties(EnableMigrationInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationInputProperties.java new file mode 100644 index 0000000000000..3952691ad398a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationInputProperties.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Enable migration input properties. + */ +public class EnableMigrationInputProperties { + /** + * The policy Id. + */ + @JsonProperty(value = "policyId", required = true) + private String policyId; + + /** + * The provider specific details. + */ + @JsonProperty(value = "providerSpecificDetails", required = true) + private EnableMigrationProviderSpecificInput providerSpecificDetails; + + /** + * Get the policy Id. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Set the policy Id. + * + * @param policyId the policyId value to set + * @return the EnableMigrationInputProperties object itself. + */ + public EnableMigrationInputProperties withPolicyId(String policyId) { + this.policyId = policyId; + return this; + } + + /** + * Get the provider specific details. + * + * @return the providerSpecificDetails value + */ + public EnableMigrationProviderSpecificInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific details. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the EnableMigrationInputProperties object itself. + */ + public EnableMigrationInputProperties withProviderSpecificDetails(EnableMigrationProviderSpecificInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationProviderSpecificInput.java new file mode 100644 index 0000000000000..66d26dca0b382 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableMigrationProviderSpecificInput.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Enable migration provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("EnableMigrationProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "VMwareCbt", value = VMwareCbtEnableMigrationInput.class) +}) +public class EnableMigrationProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionInput.java new file mode 100644 index 0000000000000..de3af51dd93d2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Enable protection input. + */ +public class EnableProtectionInput { + /** + * Enable protection input properties. + */ + @JsonProperty(value = "properties") + private EnableProtectionInputProperties properties; + + /** + * Get enable protection input properties. + * + * @return the properties value + */ + public EnableProtectionInputProperties properties() { + return this.properties; + } + + /** + * Set enable protection input properties. + * + * @param properties the properties value to set + * @return the EnableProtectionInput object itself. + */ + public EnableProtectionInput withProperties(EnableProtectionInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionInputProperties.java new file mode 100644 index 0000000000000..5684f633e59de --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionInputProperties.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Enable protection input properties. + */ +public class EnableProtectionInputProperties { + /** + * The Policy Id. + */ + @JsonProperty(value = "policyId") + private String policyId; + + /** + * The protectable item Id. + */ + @JsonProperty(value = "protectableItemId") + private String protectableItemId; + + /** + * The ReplicationProviderInput. For HyperVReplicaAzure provider, it will + * be AzureEnableProtectionInput object. For San provider, it will be + * SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can + * be null. + */ + @JsonProperty(value = "providerSpecificDetails") + private EnableProtectionProviderSpecificInput providerSpecificDetails; + + /** + * Get the Policy Id. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Set the Policy Id. + * + * @param policyId the policyId value to set + * @return the EnableProtectionInputProperties object itself. + */ + public EnableProtectionInputProperties withPolicyId(String policyId) { + this.policyId = policyId; + return this; + } + + /** + * Get the protectable item Id. + * + * @return the protectableItemId value + */ + public String protectableItemId() { + return this.protectableItemId; + } + + /** + * Set the protectable item Id. + * + * @param protectableItemId the protectableItemId value to set + * @return the EnableProtectionInputProperties object itself. + */ + public EnableProtectionInputProperties withProtectableItemId(String protectableItemId) { + this.protectableItemId = protectableItemId; + return this; + } + + /** + * Get the ReplicationProviderInput. For HyperVReplicaAzure provider, it will be AzureEnableProtectionInput object. For San provider, it will be SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can be null. + * + * @return the providerSpecificDetails value + */ + public EnableProtectionProviderSpecificInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the ReplicationProviderInput. For HyperVReplicaAzure provider, it will be AzureEnableProtectionInput object. For San provider, it will be SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can be null. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the EnableProtectionInputProperties object itself. + */ + public EnableProtectionInputProperties withProviderSpecificDetails(EnableProtectionProviderSpecificInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionProviderSpecificInput.java new file mode 100644 index 0000000000000..4c25e83bd9b8d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EnableProtectionProviderSpecificInput.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Enable protection provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("EnableProtectionProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AEnableProtectionInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzureEnableProtectionInput.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2EnableProtectionInput.class), + @JsonSubTypes.Type(name = "InMage", value = InMageEnableProtectionInput.class), + @JsonSubTypes.Type(name = "San", value = SanEnableProtectionInput.class) +}) +public class EnableProtectionProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EncryptionDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EncryptionDetails.java new file mode 100644 index 0000000000000..443a5c64ee7dd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EncryptionDetails.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Encryption details for the fabric. + */ +public class EncryptionDetails { + /** + * The key encryption key state for the Vmm. + */ + @JsonProperty(value = "kekState") + private String kekState; + + /** + * The key encryption key certificate thumbprint. + */ + @JsonProperty(value = "kekCertThumbprint") + private String kekCertThumbprint; + + /** + * The key encryption key certificate expiry date. + */ + @JsonProperty(value = "kekCertExpiryDate") + private DateTime kekCertExpiryDate; + + /** + * Get the key encryption key state for the Vmm. + * + * @return the kekState value + */ + public String kekState() { + return this.kekState; + } + + /** + * Set the key encryption key state for the Vmm. + * + * @param kekState the kekState value to set + * @return the EncryptionDetails object itself. + */ + public EncryptionDetails withKekState(String kekState) { + this.kekState = kekState; + return this; + } + + /** + * Get the key encryption key certificate thumbprint. + * + * @return the kekCertThumbprint value + */ + public String kekCertThumbprint() { + return this.kekCertThumbprint; + } + + /** + * Set the key encryption key certificate thumbprint. + * + * @param kekCertThumbprint the kekCertThumbprint value to set + * @return the EncryptionDetails object itself. + */ + public EncryptionDetails withKekCertThumbprint(String kekCertThumbprint) { + this.kekCertThumbprint = kekCertThumbprint; + return this; + } + + /** + * Get the key encryption key certificate expiry date. + * + * @return the kekCertExpiryDate value + */ + public DateTime kekCertExpiryDate() { + return this.kekCertExpiryDate; + } + + /** + * Set the key encryption key certificate expiry date. + * + * @param kekCertExpiryDate the kekCertExpiryDate value to set + * @return the EncryptionDetails object itself. + */ + public EncryptionDetails withKekCertExpiryDate(DateTime kekCertExpiryDate) { + this.kekCertExpiryDate = kekCertExpiryDate; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EthernetAddressType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EthernetAddressType.java new file mode 100644 index 0000000000000..a4b0edb0550a9 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EthernetAddressType.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for EthernetAddressType. + */ +public final class EthernetAddressType extends ExpandableStringEnum { + /** Static value Dynamic for EthernetAddressType. */ + public static final EthernetAddressType DYNAMIC = fromString("Dynamic"); + + /** Static value Static for EthernetAddressType. */ + public static final EthernetAddressType STATIC = fromString("Static"); + + /** + * Creates or finds a EthernetAddressType from its string representation. + * @param name a name to look for + * @return the corresponding EthernetAddressType + */ + @JsonCreator + public static EthernetAddressType fromString(String name) { + return fromString(name, EthernetAddressType.class); + } + + /** + * @return known EthernetAddressType values + */ + public static Collection values() { + return values(EthernetAddressType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Event.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Event.java new file mode 100644 index 0000000000000..773983ab15801 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Event.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.EventInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing Event. + */ +public interface Event extends HasInner, Indexable, Refreshable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + EventProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventProperties.java new file mode 100644 index 0000000000000..36d5892d9d3ba --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventProperties.java @@ -0,0 +1,282 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The properties of a monitoring event. + */ +public class EventProperties { + /** + * The Id of the monitoring event. + */ + @JsonProperty(value = "eventCode") + private String eventCode; + + /** + * The event name. + */ + @JsonProperty(value = "description") + private String description; + + /** + * The type of the event. for example: VM Health, Server Health, Job + * Failure etc. + */ + @JsonProperty(value = "eventType") + private String eventType; + + /** + * The friendly name of the source of the event on which it is raised (for + * example, VM, VMM etc). + */ + @JsonProperty(value = "affectedObjectFriendlyName") + private String affectedObjectFriendlyName; + + /** + * The severity of the event. + */ + @JsonProperty(value = "severity") + private String severity; + + /** + * The time of occurrence of the event. + */ + @JsonProperty(value = "timeOfOccurrence") + private DateTime timeOfOccurrence; + + /** + * The ARM ID of the fabric. + */ + @JsonProperty(value = "fabricId") + private String fabricId; + + /** + * The provider specific settings. + */ + @JsonProperty(value = "providerSpecificDetails") + private EventProviderSpecificDetails providerSpecificDetails; + + /** + * The event specific settings. + */ + @JsonProperty(value = "eventSpecificDetails") + private EventSpecificDetails eventSpecificDetails; + + /** + * The list of errors / warnings capturing details associated with the + * issue(s). + */ + @JsonProperty(value = "healthErrors") + private List healthErrors; + + /** + * Get the Id of the monitoring event. + * + * @return the eventCode value + */ + public String eventCode() { + return this.eventCode; + } + + /** + * Set the Id of the monitoring event. + * + * @param eventCode the eventCode value to set + * @return the EventProperties object itself. + */ + public EventProperties withEventCode(String eventCode) { + this.eventCode = eventCode; + return this; + } + + /** + * Get the event name. + * + * @return the description value + */ + public String description() { + return this.description; + } + + /** + * Set the event name. + * + * @param description the description value to set + * @return the EventProperties object itself. + */ + public EventProperties withDescription(String description) { + this.description = description; + return this; + } + + /** + * Get the type of the event. for example: VM Health, Server Health, Job Failure etc. + * + * @return the eventType value + */ + public String eventType() { + return this.eventType; + } + + /** + * Set the type of the event. for example: VM Health, Server Health, Job Failure etc. + * + * @param eventType the eventType value to set + * @return the EventProperties object itself. + */ + public EventProperties withEventType(String eventType) { + this.eventType = eventType; + return this; + } + + /** + * Get the friendly name of the source of the event on which it is raised (for example, VM, VMM etc). + * + * @return the affectedObjectFriendlyName value + */ + public String affectedObjectFriendlyName() { + return this.affectedObjectFriendlyName; + } + + /** + * Set the friendly name of the source of the event on which it is raised (for example, VM, VMM etc). + * + * @param affectedObjectFriendlyName the affectedObjectFriendlyName value to set + * @return the EventProperties object itself. + */ + public EventProperties withAffectedObjectFriendlyName(String affectedObjectFriendlyName) { + this.affectedObjectFriendlyName = affectedObjectFriendlyName; + return this; + } + + /** + * Get the severity of the event. + * + * @return the severity value + */ + public String severity() { + return this.severity; + } + + /** + * Set the severity of the event. + * + * @param severity the severity value to set + * @return the EventProperties object itself. + */ + public EventProperties withSeverity(String severity) { + this.severity = severity; + return this; + } + + /** + * Get the time of occurrence of the event. + * + * @return the timeOfOccurrence value + */ + public DateTime timeOfOccurrence() { + return this.timeOfOccurrence; + } + + /** + * Set the time of occurrence of the event. + * + * @param timeOfOccurrence the timeOfOccurrence value to set + * @return the EventProperties object itself. + */ + public EventProperties withTimeOfOccurrence(DateTime timeOfOccurrence) { + this.timeOfOccurrence = timeOfOccurrence; + return this; + } + + /** + * Get the ARM ID of the fabric. + * + * @return the fabricId value + */ + public String fabricId() { + return this.fabricId; + } + + /** + * Set the ARM ID of the fabric. + * + * @param fabricId the fabricId value to set + * @return the EventProperties object itself. + */ + public EventProperties withFabricId(String fabricId) { + this.fabricId = fabricId; + return this; + } + + /** + * Get the provider specific settings. + * + * @return the providerSpecificDetails value + */ + public EventProviderSpecificDetails providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific settings. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the EventProperties object itself. + */ + public EventProperties withProviderSpecificDetails(EventProviderSpecificDetails providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + + /** + * Get the event specific settings. + * + * @return the eventSpecificDetails value + */ + public EventSpecificDetails eventSpecificDetails() { + return this.eventSpecificDetails; + } + + /** + * Set the event specific settings. + * + * @param eventSpecificDetails the eventSpecificDetails value to set + * @return the EventProperties object itself. + */ + public EventProperties withEventSpecificDetails(EventSpecificDetails eventSpecificDetails) { + this.eventSpecificDetails = eventSpecificDetails; + return this; + } + + /** + * Get the list of errors / warnings capturing details associated with the issue(s). + * + * @return the healthErrors value + */ + public List healthErrors() { + return this.healthErrors; + } + + /** + * Set the list of errors / warnings capturing details associated with the issue(s). + * + * @param healthErrors the healthErrors value to set + * @return the EventProperties object itself. + */ + public EventProperties withHealthErrors(List healthErrors) { + this.healthErrors = healthErrors; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventProviderSpecificDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventProviderSpecificDetails.java new file mode 100644 index 0000000000000..a00eb3e27debf --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventProviderSpecificDetails.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Model class for provider specific details for an event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("EventProviderSpecificDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AEventDetails.class), + @JsonSubTypes.Type(name = "HyperVReplica2012", value = HyperVReplica2012EventDetails.class), + @JsonSubTypes.Type(name = "HyperVReplica2012R2", value = HyperVReplica2012R2EventDetails.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzureEventDetails.class), + @JsonSubTypes.Type(name = "HyperVReplicaBaseEventDetails", value = HyperVReplicaBaseEventDetails.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2EventDetails.class) +}) +public class EventProviderSpecificDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventQueryParameter.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventQueryParameter.java new file mode 100644 index 0000000000000..17fe45f39f270 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventQueryParameter.java @@ -0,0 +1,202 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Implements the event query parameter. + */ +public class EventQueryParameter { + /** + * The source id of the events to be queried. + */ + @JsonProperty(value = "eventCode") + private String eventCode; + + /** + * The severity of the events to be queried. + */ + @JsonProperty(value = "severity") + private String severity; + + /** + * The type of the events to be queried. + */ + @JsonProperty(value = "eventType") + private String eventType; + + /** + * The affected object server id of the events to be queried. + */ + @JsonProperty(value = "fabricName") + private String fabricName; + + /** + * The affected object name of the events to be queried. + */ + @JsonProperty(value = "affectedObjectFriendlyName") + private String affectedObjectFriendlyName; + + /** + * The start time of the time range within which the events are to be + * queried. + */ + @JsonProperty(value = "startTime") + private DateTime startTime; + + /** + * The end time of the time range within which the events are to be + * queried. + */ + @JsonProperty(value = "endTime") + private DateTime endTime; + + /** + * Get the source id of the events to be queried. + * + * @return the eventCode value + */ + public String eventCode() { + return this.eventCode; + } + + /** + * Set the source id of the events to be queried. + * + * @param eventCode the eventCode value to set + * @return the EventQueryParameter object itself. + */ + public EventQueryParameter withEventCode(String eventCode) { + this.eventCode = eventCode; + return this; + } + + /** + * Get the severity of the events to be queried. + * + * @return the severity value + */ + public String severity() { + return this.severity; + } + + /** + * Set the severity of the events to be queried. + * + * @param severity the severity value to set + * @return the EventQueryParameter object itself. + */ + public EventQueryParameter withSeverity(String severity) { + this.severity = severity; + return this; + } + + /** + * Get the type of the events to be queried. + * + * @return the eventType value + */ + public String eventType() { + return this.eventType; + } + + /** + * Set the type of the events to be queried. + * + * @param eventType the eventType value to set + * @return the EventQueryParameter object itself. + */ + public EventQueryParameter withEventType(String eventType) { + this.eventType = eventType; + return this; + } + + /** + * Get the affected object server id of the events to be queried. + * + * @return the fabricName value + */ + public String fabricName() { + return this.fabricName; + } + + /** + * Set the affected object server id of the events to be queried. + * + * @param fabricName the fabricName value to set + * @return the EventQueryParameter object itself. + */ + public EventQueryParameter withFabricName(String fabricName) { + this.fabricName = fabricName; + return this; + } + + /** + * Get the affected object name of the events to be queried. + * + * @return the affectedObjectFriendlyName value + */ + public String affectedObjectFriendlyName() { + return this.affectedObjectFriendlyName; + } + + /** + * Set the affected object name of the events to be queried. + * + * @param affectedObjectFriendlyName the affectedObjectFriendlyName value to set + * @return the EventQueryParameter object itself. + */ + public EventQueryParameter withAffectedObjectFriendlyName(String affectedObjectFriendlyName) { + this.affectedObjectFriendlyName = affectedObjectFriendlyName; + return this; + } + + /** + * Get the start time of the time range within which the events are to be queried. + * + * @return the startTime value + */ + public DateTime startTime() { + return this.startTime; + } + + /** + * Set the start time of the time range within which the events are to be queried. + * + * @param startTime the startTime value to set + * @return the EventQueryParameter object itself. + */ + public EventQueryParameter withStartTime(DateTime startTime) { + this.startTime = startTime; + return this; + } + + /** + * Get the end time of the time range within which the events are to be queried. + * + * @return the endTime value + */ + public DateTime endTime() { + return this.endTime; + } + + /** + * Set the end time of the time range within which the events are to be queried. + * + * @param endTime the endTime value to set + * @return the EventQueryParameter object itself. + */ + public EventQueryParameter withEndTime(DateTime endTime) { + this.endTime = endTime; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventSpecificDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventSpecificDetails.java new file mode 100644 index 0000000000000..76784fc4c1f2a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EventSpecificDetails.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Model class for event specific details for an event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("EventSpecificDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "JobStatus", value = JobStatusEventDetails.class) +}) +public class EventSpecificDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ExportJobDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ExportJobDetails.java new file mode 100644 index 0000000000000..d089eec7e8348 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ExportJobDetails.java @@ -0,0 +1,73 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents details for export jobs workflow. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ExportJobDetails") +public class ExportJobDetails extends JobDetails { + /** + * BlobUri of the exported jobs. + */ + @JsonProperty(value = "blobUri") + private String blobUri; + + /** + * The sas token to access blob. + */ + @JsonProperty(value = "sasToken") + private String sasToken; + + /** + * Get blobUri of the exported jobs. + * + * @return the blobUri value + */ + public String blobUri() { + return this.blobUri; + } + + /** + * Set blobUri of the exported jobs. + * + * @param blobUri the blobUri value to set + * @return the ExportJobDetails object itself. + */ + public ExportJobDetails withBlobUri(String blobUri) { + this.blobUri = blobUri; + return this; + } + + /** + * Get the sas token to access blob. + * + * @return the sasToken value + */ + public String sasToken() { + return this.sasToken; + } + + /** + * Set the sas token to access blob. + * + * @param sasToken the sasToken value to set + * @return the ExportJobDetails object itself. + */ + public ExportJobDetails withSasToken(String sasToken) { + this.sasToken = sasToken; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Fabric.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Fabric.java new file mode 100644 index 0000000000000..c70720d12d1ec --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Fabric.java @@ -0,0 +1,120 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.FabricInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing Fabric. + */ +public interface Fabric extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + FabricProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the Fabric definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithVault, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of Fabric definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a Fabric definition. + */ + interface Blank extends WithVault { + } + + /** + * The stage of the fabric definition allowing to specify Vault. + */ + interface WithVault { + /** + * Specifies . + * @return the next definition stage + */ + WithProperties withExistingVault(); + } + + /** + * The stage of the fabric definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Fabric creation input + * @return the next definition stage + */ + WithCreate withProperties(FabricCreationInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a Fabric update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of Fabric update stages. + */ + interface UpdateStages { + /** + * The stage of the fabric update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Fabric creation input + * @return the next update stage + */ + Update withProperties(FabricCreationInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricCreationInput.java new file mode 100644 index 0000000000000..4c70c5e4f1328 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricCreationInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Site details provided during the time of site creation. + */ +public class FabricCreationInput { + /** + * Fabric creation input. + */ + @JsonProperty(value = "properties") + private FabricCreationInputProperties properties; + + /** + * Get fabric creation input. + * + * @return the properties value + */ + public FabricCreationInputProperties properties() { + return this.properties; + } + + /** + * Set fabric creation input. + * + * @param properties the properties value to set + * @return the FabricCreationInput object itself. + */ + public FabricCreationInput withProperties(FabricCreationInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricCreationInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricCreationInputProperties.java new file mode 100644 index 0000000000000..c94d806e5877a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricCreationInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Properties of site details provided during the time of site creation. + */ +public class FabricCreationInputProperties { + /** + * Fabric provider specific creation input. + */ + @JsonProperty(value = "customDetails") + private FabricSpecificCreationInput customDetails; + + /** + * Get fabric provider specific creation input. + * + * @return the customDetails value + */ + public FabricSpecificCreationInput customDetails() { + return this.customDetails; + } + + /** + * Set fabric provider specific creation input. + * + * @param customDetails the customDetails value to set + * @return the FabricCreationInputProperties object itself. + */ + public FabricCreationInputProperties withCustomDetails(FabricSpecificCreationInput customDetails) { + this.customDetails = customDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricProperties.java new file mode 100644 index 0000000000000..24485df830e6a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricProperties.java @@ -0,0 +1,226 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Fabric properties. + */ +public class FabricProperties { + /** + * Friendly name of the fabric. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * Encryption details for the fabric. + */ + @JsonProperty(value = "encryptionDetails") + private EncryptionDetails encryptionDetails; + + /** + * Rollover encryption details for the fabric. + */ + @JsonProperty(value = "rolloverEncryptionDetails") + private EncryptionDetails rolloverEncryptionDetails; + + /** + * Dra Registration Id. + */ + @JsonProperty(value = "internalIdentifier") + private String internalIdentifier; + + /** + * BCDR state of the fabric. + */ + @JsonProperty(value = "bcdrState") + private String bcdrState; + + /** + * Fabric specific settings. + */ + @JsonProperty(value = "customDetails") + private FabricSpecificDetails customDetails; + + /** + * Fabric health error details. + */ + @JsonProperty(value = "healthErrorDetails") + private List healthErrorDetails; + + /** + * Health of fabric. + */ + @JsonProperty(value = "health") + private String health; + + /** + * Get friendly name of the fabric. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set friendly name of the fabric. + * + * @param friendlyName the friendlyName value to set + * @return the FabricProperties object itself. + */ + public FabricProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get encryption details for the fabric. + * + * @return the encryptionDetails value + */ + public EncryptionDetails encryptionDetails() { + return this.encryptionDetails; + } + + /** + * Set encryption details for the fabric. + * + * @param encryptionDetails the encryptionDetails value to set + * @return the FabricProperties object itself. + */ + public FabricProperties withEncryptionDetails(EncryptionDetails encryptionDetails) { + this.encryptionDetails = encryptionDetails; + return this; + } + + /** + * Get rollover encryption details for the fabric. + * + * @return the rolloverEncryptionDetails value + */ + public EncryptionDetails rolloverEncryptionDetails() { + return this.rolloverEncryptionDetails; + } + + /** + * Set rollover encryption details for the fabric. + * + * @param rolloverEncryptionDetails the rolloverEncryptionDetails value to set + * @return the FabricProperties object itself. + */ + public FabricProperties withRolloverEncryptionDetails(EncryptionDetails rolloverEncryptionDetails) { + this.rolloverEncryptionDetails = rolloverEncryptionDetails; + return this; + } + + /** + * Get dra Registration Id. + * + * @return the internalIdentifier value + */ + public String internalIdentifier() { + return this.internalIdentifier; + } + + /** + * Set dra Registration Id. + * + * @param internalIdentifier the internalIdentifier value to set + * @return the FabricProperties object itself. + */ + public FabricProperties withInternalIdentifier(String internalIdentifier) { + this.internalIdentifier = internalIdentifier; + return this; + } + + /** + * Get bCDR state of the fabric. + * + * @return the bcdrState value + */ + public String bcdrState() { + return this.bcdrState; + } + + /** + * Set bCDR state of the fabric. + * + * @param bcdrState the bcdrState value to set + * @return the FabricProperties object itself. + */ + public FabricProperties withBcdrState(String bcdrState) { + this.bcdrState = bcdrState; + return this; + } + + /** + * Get fabric specific settings. + * + * @return the customDetails value + */ + public FabricSpecificDetails customDetails() { + return this.customDetails; + } + + /** + * Set fabric specific settings. + * + * @param customDetails the customDetails value to set + * @return the FabricProperties object itself. + */ + public FabricProperties withCustomDetails(FabricSpecificDetails customDetails) { + this.customDetails = customDetails; + return this; + } + + /** + * Get fabric health error details. + * + * @return the healthErrorDetails value + */ + public List healthErrorDetails() { + return this.healthErrorDetails; + } + + /** + * Set fabric health error details. + * + * @param healthErrorDetails the healthErrorDetails value to set + * @return the FabricProperties object itself. + */ + public FabricProperties withHealthErrorDetails(List healthErrorDetails) { + this.healthErrorDetails = healthErrorDetails; + return this; + } + + /** + * Get health of fabric. + * + * @return the health value + */ + public String health() { + return this.health; + } + + /** + * Set health of fabric. + * + * @param health the health value to set + * @return the FabricProperties object itself. + */ + public FabricProperties withHealth(String health) { + this.health = health; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricReplicationGroupTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricReplicationGroupTaskDetails.java new file mode 100644 index 0000000000000..dd38966fea89e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricReplicationGroupTaskDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the fabric replication group task details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("FabricReplicationGroupTaskDetails") +public class FabricReplicationGroupTaskDetails extends TaskTypeDetails { + /** + * The skipped reason. + */ + @JsonProperty(value = "skippedReason") + private String skippedReason; + + /** + * The skipped reason string. + */ + @JsonProperty(value = "skippedReasonString") + private String skippedReasonString; + + /** + * The job entity. + */ + @JsonProperty(value = "jobTask") + private JobEntity jobTask; + + /** + * Get the skipped reason. + * + * @return the skippedReason value + */ + public String skippedReason() { + return this.skippedReason; + } + + /** + * Set the skipped reason. + * + * @param skippedReason the skippedReason value to set + * @return the FabricReplicationGroupTaskDetails object itself. + */ + public FabricReplicationGroupTaskDetails withSkippedReason(String skippedReason) { + this.skippedReason = skippedReason; + return this; + } + + /** + * Get the skipped reason string. + * + * @return the skippedReasonString value + */ + public String skippedReasonString() { + return this.skippedReasonString; + } + + /** + * Set the skipped reason string. + * + * @param skippedReasonString the skippedReasonString value to set + * @return the FabricReplicationGroupTaskDetails object itself. + */ + public FabricReplicationGroupTaskDetails withSkippedReasonString(String skippedReasonString) { + this.skippedReasonString = skippedReasonString; + return this; + } + + /** + * Get the job entity. + * + * @return the jobTask value + */ + public JobEntity jobTask() { + return this.jobTask; + } + + /** + * Set the job entity. + * + * @param jobTask the jobTask value to set + * @return the FabricReplicationGroupTaskDetails object itself. + */ + public FabricReplicationGroupTaskDetails withJobTask(JobEntity jobTask) { + this.jobTask = jobTask; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificCreateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificCreateNetworkMappingInput.java new file mode 100644 index 0000000000000..d0bc7974d4366 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificCreateNetworkMappingInput.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Input details specific to fabrics during Network Mapping. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("FabricSpecificCreateNetworkMappingInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "AzureToAzure", value = AzureToAzureCreateNetworkMappingInput.class), + @JsonSubTypes.Type(name = "VmmToAzure", value = VmmToAzureCreateNetworkMappingInput.class), + @JsonSubTypes.Type(name = "VmmToVmm", value = VmmToVmmCreateNetworkMappingInput.class) +}) +public class FabricSpecificCreateNetworkMappingInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificCreationInput.java new file mode 100644 index 0000000000000..38f4d5e50555f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificCreationInput.java @@ -0,0 +1,25 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Fabric provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("FabricSpecificCreationInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "Azure", value = AzureFabricCreationInput.class), + @JsonSubTypes.Type(name = "VMwareV2", value = VMwareV2FabricCreationInput.class) +}) +public class FabricSpecificCreationInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificDetails.java new file mode 100644 index 0000000000000..c1a7c96ff9ffd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificDetails.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Fabric specific details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("FabricSpecificDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "Azure", value = AzureFabricSpecificDetails.class), + @JsonSubTypes.Type(name = "HyperVSite", value = HyperVSiteDetails.class), + @JsonSubTypes.Type(name = "VMM", value = VmmDetails.class), + @JsonSubTypes.Type(name = "VMware", value = VMwareDetails.class), + @JsonSubTypes.Type(name = "VMwareV2", value = VMwareV2FabricSpecificDetails.class) +}) +public class FabricSpecificDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificUpdateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificUpdateNetworkMappingInput.java new file mode 100644 index 0000000000000..819dce093fe91 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FabricSpecificUpdateNetworkMappingInput.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Input details specific to fabrics during Network Mapping. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("FabricSpecificUpdateNetworkMappingInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "AzureToAzure", value = AzureToAzureUpdateNetworkMappingInput.class), + @JsonSubTypes.Type(name = "VmmToAzure", value = VmmToAzureUpdateNetworkMappingInput.class), + @JsonSubTypes.Type(name = "VmmToVmm", value = VmmToVmmUpdateNetworkMappingInput.class) +}) +public class FabricSpecificUpdateNetworkMappingInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverDeploymentModel.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverDeploymentModel.java new file mode 100644 index 0000000000000..0e7e2004f60af --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverDeploymentModel.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for FailoverDeploymentModel. + */ +public final class FailoverDeploymentModel extends ExpandableStringEnum { + /** Static value NotApplicable for FailoverDeploymentModel. */ + public static final FailoverDeploymentModel NOT_APPLICABLE = fromString("NotApplicable"); + + /** Static value Classic for FailoverDeploymentModel. */ + public static final FailoverDeploymentModel CLASSIC = fromString("Classic"); + + /** Static value ResourceManager for FailoverDeploymentModel. */ + public static final FailoverDeploymentModel RESOURCE_MANAGER = fromString("ResourceManager"); + + /** + * Creates or finds a FailoverDeploymentModel from its string representation. + * @param name a name to look for + * @return the corresponding FailoverDeploymentModel + */ + @JsonCreator + public static FailoverDeploymentModel fromString(String name) { + return fromString(name, FailoverDeploymentModel.class); + } + + /** + * @return known FailoverDeploymentModel values + */ + public static Collection values() { + return values(FailoverDeploymentModel.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverJobDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverJobDetails.java new file mode 100644 index 0000000000000..6124671bc3484 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverJobDetails.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the details for a failover job. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("FailoverJobDetails") +public class FailoverJobDetails extends JobDetails { + /** + * The test VM details. + */ + @JsonProperty(value = "protectedItemDetails") + private List protectedItemDetails; + + /** + * Get the test VM details. + * + * @return the protectedItemDetails value + */ + public List protectedItemDetails() { + return this.protectedItemDetails; + } + + /** + * Set the test VM details. + * + * @param protectedItemDetails the protectedItemDetails value to set + * @return the FailoverJobDetails object itself. + */ + public FailoverJobDetails withProtectedItemDetails(List protectedItemDetails) { + this.protectedItemDetails = protectedItemDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverProcessServerRequest.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverProcessServerRequest.java new file mode 100644 index 0000000000000..983a972050876 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverProcessServerRequest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Request to failover a process server. + */ +public class FailoverProcessServerRequest { + /** + * The properties of the PS Failover request. + */ + @JsonProperty(value = "properties") + private FailoverProcessServerRequestProperties properties; + + /** + * Get the properties of the PS Failover request. + * + * @return the properties value + */ + public FailoverProcessServerRequestProperties properties() { + return this.properties; + } + + /** + * Set the properties of the PS Failover request. + * + * @param properties the properties value to set + * @return the FailoverProcessServerRequest object itself. + */ + public FailoverProcessServerRequest withProperties(FailoverProcessServerRequestProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverProcessServerRequestProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverProcessServerRequestProperties.java new file mode 100644 index 0000000000000..45293e889626c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverProcessServerRequestProperties.java @@ -0,0 +1,148 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The properties of the Failover Process Server request. + */ +public class FailoverProcessServerRequestProperties { + /** + * The container identifier. + */ + @JsonProperty(value = "containerName") + private String containerName; + + /** + * The source process server. + */ + @JsonProperty(value = "sourceProcessServerId") + private String sourceProcessServerId; + + /** + * The new process server. + */ + @JsonProperty(value = "targetProcessServerId") + private String targetProcessServerId; + + /** + * The VMS to migrate. + */ + @JsonProperty(value = "vmsToMigrate") + private List vmsToMigrate; + + /** + * A value for failover type. It can be systemlevel/serverlevel. + */ + @JsonProperty(value = "updateType") + private String updateType; + + /** + * Get the container identifier. + * + * @return the containerName value + */ + public String containerName() { + return this.containerName; + } + + /** + * Set the container identifier. + * + * @param containerName the containerName value to set + * @return the FailoverProcessServerRequestProperties object itself. + */ + public FailoverProcessServerRequestProperties withContainerName(String containerName) { + this.containerName = containerName; + return this; + } + + /** + * Get the source process server. + * + * @return the sourceProcessServerId value + */ + public String sourceProcessServerId() { + return this.sourceProcessServerId; + } + + /** + * Set the source process server. + * + * @param sourceProcessServerId the sourceProcessServerId value to set + * @return the FailoverProcessServerRequestProperties object itself. + */ + public FailoverProcessServerRequestProperties withSourceProcessServerId(String sourceProcessServerId) { + this.sourceProcessServerId = sourceProcessServerId; + return this; + } + + /** + * Get the new process server. + * + * @return the targetProcessServerId value + */ + public String targetProcessServerId() { + return this.targetProcessServerId; + } + + /** + * Set the new process server. + * + * @param targetProcessServerId the targetProcessServerId value to set + * @return the FailoverProcessServerRequestProperties object itself. + */ + public FailoverProcessServerRequestProperties withTargetProcessServerId(String targetProcessServerId) { + this.targetProcessServerId = targetProcessServerId; + return this; + } + + /** + * Get the VMS to migrate. + * + * @return the vmsToMigrate value + */ + public List vmsToMigrate() { + return this.vmsToMigrate; + } + + /** + * Set the VMS to migrate. + * + * @param vmsToMigrate the vmsToMigrate value to set + * @return the FailoverProcessServerRequestProperties object itself. + */ + public FailoverProcessServerRequestProperties withVmsToMigrate(List vmsToMigrate) { + this.vmsToMigrate = vmsToMigrate; + return this; + } + + /** + * Get a value for failover type. It can be systemlevel/serverlevel. + * + * @return the updateType value + */ + public String updateType() { + return this.updateType; + } + + /** + * Set a value for failover type. It can be systemlevel/serverlevel. + * + * @param updateType the updateType value to set + * @return the FailoverProcessServerRequestProperties object itself. + */ + public FailoverProcessServerRequestProperties withUpdateType(String updateType) { + this.updateType = updateType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverReplicationProtectedItemDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverReplicationProtectedItemDetails.java new file mode 100644 index 0000000000000..69f20f4b2d4a2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/FailoverReplicationProtectedItemDetails.java @@ -0,0 +1,252 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Failover details for a replication protected item. + */ +public class FailoverReplicationProtectedItemDetails { + /** + * The name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The friendly name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The test Vm name. + */ + @JsonProperty(value = "testVmName") + private String testVmName; + + /** + * The test Vm friendly name. + */ + @JsonProperty(value = "testVmFriendlyName") + private String testVmFriendlyName; + + /** + * The network connection status. + */ + @JsonProperty(value = "networkConnectionStatus") + private String networkConnectionStatus; + + /** + * The network friendly name. + */ + @JsonProperty(value = "networkFriendlyName") + private String networkFriendlyName; + + /** + * The network subnet. + */ + @JsonProperty(value = "subnet") + private String subnet; + + /** + * The recovery point Id. + */ + @JsonProperty(value = "recoveryPointId") + private String recoveryPointId; + + /** + * The recovery point time. + */ + @JsonProperty(value = "recoveryPointTime") + private DateTime recoveryPointTime; + + /** + * Get the name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name. + * + * @param name the name value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withName(String name) { + this.name = name; + return this; + } + + /** + * Get the friendly name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the friendly name. + * + * @param friendlyName the friendlyName value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the test Vm name. + * + * @return the testVmName value + */ + public String testVmName() { + return this.testVmName; + } + + /** + * Set the test Vm name. + * + * @param testVmName the testVmName value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withTestVmName(String testVmName) { + this.testVmName = testVmName; + return this; + } + + /** + * Get the test Vm friendly name. + * + * @return the testVmFriendlyName value + */ + public String testVmFriendlyName() { + return this.testVmFriendlyName; + } + + /** + * Set the test Vm friendly name. + * + * @param testVmFriendlyName the testVmFriendlyName value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withTestVmFriendlyName(String testVmFriendlyName) { + this.testVmFriendlyName = testVmFriendlyName; + return this; + } + + /** + * Get the network connection status. + * + * @return the networkConnectionStatus value + */ + public String networkConnectionStatus() { + return this.networkConnectionStatus; + } + + /** + * Set the network connection status. + * + * @param networkConnectionStatus the networkConnectionStatus value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withNetworkConnectionStatus(String networkConnectionStatus) { + this.networkConnectionStatus = networkConnectionStatus; + return this; + } + + /** + * Get the network friendly name. + * + * @return the networkFriendlyName value + */ + public String networkFriendlyName() { + return this.networkFriendlyName; + } + + /** + * Set the network friendly name. + * + * @param networkFriendlyName the networkFriendlyName value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withNetworkFriendlyName(String networkFriendlyName) { + this.networkFriendlyName = networkFriendlyName; + return this; + } + + /** + * Get the network subnet. + * + * @return the subnet value + */ + public String subnet() { + return this.subnet; + } + + /** + * Set the network subnet. + * + * @param subnet the subnet value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withSubnet(String subnet) { + this.subnet = subnet; + return this; + } + + /** + * Get the recovery point Id. + * + * @return the recoveryPointId value + */ + public String recoveryPointId() { + return this.recoveryPointId; + } + + /** + * Set the recovery point Id. + * + * @param recoveryPointId the recoveryPointId value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withRecoveryPointId(String recoveryPointId) { + this.recoveryPointId = recoveryPointId; + return this; + } + + /** + * Get the recovery point time. + * + * @return the recoveryPointTime value + */ + public DateTime recoveryPointTime() { + return this.recoveryPointTime; + } + + /** + * Set the recovery point time. + * + * @param recoveryPointTime the recoveryPointTime value to set + * @return the FailoverReplicationProtectedItemDetails object itself. + */ + public FailoverReplicationProtectedItemDetails withRecoveryPointTime(DateTime recoveryPointTime) { + this.recoveryPointTime = recoveryPointTime; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/GroupTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/GroupTaskDetails.java new file mode 100644 index 0000000000000..b838076fa6afb --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/GroupTaskDetails.java @@ -0,0 +1,55 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * This class represents the group task details when parent child relationship + * exists in the drill down. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("GroupTaskDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "InlineWorkflowTaskDetails", value = InlineWorkflowTaskDetails.class), + @JsonSubTypes.Type(name = "RecoveryPlanGroupTaskDetails", value = RecoveryPlanGroupTaskDetails.class), + @JsonSubTypes.Type(name = "RecoveryPlanShutdownGroupTaskDetails", value = RecoveryPlanShutdownGroupTaskDetails.class) +}) +public class GroupTaskDetails { + /** + * The child tasks. + */ + @JsonProperty(value = "childTasks") + private List childTasks; + + /** + * Get the child tasks. + * + * @return the childTasks value + */ + public List childTasks() { + return this.childTasks; + } + + /** + * Set the child tasks. + * + * @param childTasks the childTasks value to set + * @return the GroupTaskDetails object itself. + */ + public GroupTaskDetails withChildTasks(List childTasks) { + this.childTasks = childTasks; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthError.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthError.java new file mode 100644 index 0000000000000..8ff55a03a19d5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthError.java @@ -0,0 +1,362 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Health Error. + */ +public class HealthError { + /** + * The inner health errors. HealthError having a list of HealthError as + * child errors is problematic. InnerHealthError is used because this will + * prevent an infinite loop of structures when Hydra tries to auto-generate + * the contract. We are exposing the related health errors as inner health + * errors and all API consumers can utilize this in the same fashion as + * Exception -&gt; InnerException. + */ + @JsonProperty(value = "innerHealthErrors") + private List innerHealthErrors; + + /** + * Source of error. + */ + @JsonProperty(value = "errorSource") + private String errorSource; + + /** + * Type of error. + */ + @JsonProperty(value = "errorType") + private String errorType; + + /** + * Level of error. + */ + @JsonProperty(value = "errorLevel") + private String errorLevel; + + /** + * Category of error. + */ + @JsonProperty(value = "errorCategory") + private String errorCategory; + + /** + * Error code. + */ + @JsonProperty(value = "errorCode") + private String errorCode; + + /** + * Summary message of the entity. + */ + @JsonProperty(value = "summaryMessage") + private String summaryMessage; + + /** + * Error message. + */ + @JsonProperty(value = "errorMessage") + private String errorMessage; + + /** + * Possible causes of error. + */ + @JsonProperty(value = "possibleCauses") + private String possibleCauses; + + /** + * Recommended action to resolve error. + */ + @JsonProperty(value = "recommendedAction") + private String recommendedAction; + + /** + * Error creation time (UTC). + */ + @JsonProperty(value = "creationTimeUtc") + private DateTime creationTimeUtc; + + /** + * DRA error message. + */ + @JsonProperty(value = "recoveryProviderErrorMessage") + private String recoveryProviderErrorMessage; + + /** + * ID of the entity. + */ + @JsonProperty(value = "entityId") + private String entityId; + + /** + * Get the inner health errors. HealthError having a list of HealthError as child errors is problematic. InnerHealthError is used because this will prevent an infinite loop of structures when Hydra tries to auto-generate the contract. We are exposing the related health errors as inner health errors and all API consumers can utilize this in the same fashion as Exception -&gt; InnerException. + * + * @return the innerHealthErrors value + */ + public List innerHealthErrors() { + return this.innerHealthErrors; + } + + /** + * Set the inner health errors. HealthError having a list of HealthError as child errors is problematic. InnerHealthError is used because this will prevent an infinite loop of structures when Hydra tries to auto-generate the contract. We are exposing the related health errors as inner health errors and all API consumers can utilize this in the same fashion as Exception -&gt; InnerException. + * + * @param innerHealthErrors the innerHealthErrors value to set + * @return the HealthError object itself. + */ + public HealthError withInnerHealthErrors(List innerHealthErrors) { + this.innerHealthErrors = innerHealthErrors; + return this; + } + + /** + * Get source of error. + * + * @return the errorSource value + */ + public String errorSource() { + return this.errorSource; + } + + /** + * Set source of error. + * + * @param errorSource the errorSource value to set + * @return the HealthError object itself. + */ + public HealthError withErrorSource(String errorSource) { + this.errorSource = errorSource; + return this; + } + + /** + * Get type of error. + * + * @return the errorType value + */ + public String errorType() { + return this.errorType; + } + + /** + * Set type of error. + * + * @param errorType the errorType value to set + * @return the HealthError object itself. + */ + public HealthError withErrorType(String errorType) { + this.errorType = errorType; + return this; + } + + /** + * Get level of error. + * + * @return the errorLevel value + */ + public String errorLevel() { + return this.errorLevel; + } + + /** + * Set level of error. + * + * @param errorLevel the errorLevel value to set + * @return the HealthError object itself. + */ + public HealthError withErrorLevel(String errorLevel) { + this.errorLevel = errorLevel; + return this; + } + + /** + * Get category of error. + * + * @return the errorCategory value + */ + public String errorCategory() { + return this.errorCategory; + } + + /** + * Set category of error. + * + * @param errorCategory the errorCategory value to set + * @return the HealthError object itself. + */ + public HealthError withErrorCategory(String errorCategory) { + this.errorCategory = errorCategory; + return this; + } + + /** + * Get error code. + * + * @return the errorCode value + */ + public String errorCode() { + return this.errorCode; + } + + /** + * Set error code. + * + * @param errorCode the errorCode value to set + * @return the HealthError object itself. + */ + public HealthError withErrorCode(String errorCode) { + this.errorCode = errorCode; + return this; + } + + /** + * Get summary message of the entity. + * + * @return the summaryMessage value + */ + public String summaryMessage() { + return this.summaryMessage; + } + + /** + * Set summary message of the entity. + * + * @param summaryMessage the summaryMessage value to set + * @return the HealthError object itself. + */ + public HealthError withSummaryMessage(String summaryMessage) { + this.summaryMessage = summaryMessage; + return this; + } + + /** + * Get error message. + * + * @return the errorMessage value + */ + public String errorMessage() { + return this.errorMessage; + } + + /** + * Set error message. + * + * @param errorMessage the errorMessage value to set + * @return the HealthError object itself. + */ + public HealthError withErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + /** + * Get possible causes of error. + * + * @return the possibleCauses value + */ + public String possibleCauses() { + return this.possibleCauses; + } + + /** + * Set possible causes of error. + * + * @param possibleCauses the possibleCauses value to set + * @return the HealthError object itself. + */ + public HealthError withPossibleCauses(String possibleCauses) { + this.possibleCauses = possibleCauses; + return this; + } + + /** + * Get recommended action to resolve error. + * + * @return the recommendedAction value + */ + public String recommendedAction() { + return this.recommendedAction; + } + + /** + * Set recommended action to resolve error. + * + * @param recommendedAction the recommendedAction value to set + * @return the HealthError object itself. + */ + public HealthError withRecommendedAction(String recommendedAction) { + this.recommendedAction = recommendedAction; + return this; + } + + /** + * Get error creation time (UTC). + * + * @return the creationTimeUtc value + */ + public DateTime creationTimeUtc() { + return this.creationTimeUtc; + } + + /** + * Set error creation time (UTC). + * + * @param creationTimeUtc the creationTimeUtc value to set + * @return the HealthError object itself. + */ + public HealthError withCreationTimeUtc(DateTime creationTimeUtc) { + this.creationTimeUtc = creationTimeUtc; + return this; + } + + /** + * Get dRA error message. + * + * @return the recoveryProviderErrorMessage value + */ + public String recoveryProviderErrorMessage() { + return this.recoveryProviderErrorMessage; + } + + /** + * Set dRA error message. + * + * @param recoveryProviderErrorMessage the recoveryProviderErrorMessage value to set + * @return the HealthError object itself. + */ + public HealthError withRecoveryProviderErrorMessage(String recoveryProviderErrorMessage) { + this.recoveryProviderErrorMessage = recoveryProviderErrorMessage; + return this; + } + + /** + * Get iD of the entity. + * + * @return the entityId value + */ + public String entityId() { + return this.entityId; + } + + /** + * Set iD of the entity. + * + * @param entityId the entityId value to set + * @return the HealthError object itself. + */ + public HealthError withEntityId(String entityId) { + this.entityId = entityId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthErrorCategory.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthErrorCategory.java new file mode 100644 index 0000000000000..e63142156b898 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthErrorCategory.java @@ -0,0 +1,56 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for HealthErrorCategory. + */ +public final class HealthErrorCategory extends ExpandableStringEnum { + /** Static value None for HealthErrorCategory. */ + public static final HealthErrorCategory NONE = fromString("None"); + + /** Static value Replication for HealthErrorCategory. */ + public static final HealthErrorCategory REPLICATION = fromString("Replication"); + + /** Static value TestFailover for HealthErrorCategory. */ + public static final HealthErrorCategory TEST_FAILOVER = fromString("TestFailover"); + + /** Static value Configuration for HealthErrorCategory. */ + public static final HealthErrorCategory CONFIGURATION = fromString("Configuration"); + + /** Static value FabricInfrastructure for HealthErrorCategory. */ + public static final HealthErrorCategory FABRIC_INFRASTRUCTURE = fromString("FabricInfrastructure"); + + /** Static value VersionExpiry for HealthErrorCategory. */ + public static final HealthErrorCategory VERSION_EXPIRY = fromString("VersionExpiry"); + + /** Static value AgentAutoUpdate for HealthErrorCategory. */ + public static final HealthErrorCategory AGENT_AUTO_UPDATE = fromString("AgentAutoUpdate"); + + /** + * Creates or finds a HealthErrorCategory from its string representation. + * @param name a name to look for + * @return the corresponding HealthErrorCategory + */ + @JsonCreator + public static HealthErrorCategory fromString(String name) { + return fromString(name, HealthErrorCategory.class); + } + + /** + * @return known HealthErrorCategory values + */ + public static Collection values() { + return values(HealthErrorCategory.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthErrorSummary.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthErrorSummary.java new file mode 100644 index 0000000000000..1f471245e2043 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HealthErrorSummary.java @@ -0,0 +1,206 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * class to define the summary of the health error details. + */ +public class HealthErrorSummary { + /** + * The code of the health error. + */ + @JsonProperty(value = "summaryCode") + private String summaryCode; + + /** + * The category of the health error. Possible values include: 'None', + * 'Replication', 'TestFailover', 'Configuration', 'FabricInfrastructure', + * 'VersionExpiry', 'AgentAutoUpdate'. + */ + @JsonProperty(value = "category") + private HealthErrorCategory category; + + /** + * Severity of error. Possible values include: 'NONE', 'Warning', 'Error', + * 'Info'. + */ + @JsonProperty(value = "severity") + private Severity severity; + + /** + * The summary message of the health error. + */ + @JsonProperty(value = "summaryMessage") + private String summaryMessage; + + /** + * The type of affected ARM resource. + */ + @JsonProperty(value = "affectedResourceType") + private String affectedResourceType; + + /** + * The sub type of any subcomponent within the ARM resource that this might + * be applicable. Value remains null if not applicable. + */ + @JsonProperty(value = "affectedResourceSubtype") + private String affectedResourceSubtype; + + /** + * The list of affected resource correlation Ids. This can be used to + * uniquely identify the count of items affected by a specific category and + * severity as well as count of item affected by an specific issue. + */ + @JsonProperty(value = "affectedResourceCorrelationIds") + private List affectedResourceCorrelationIds; + + /** + * Get the code of the health error. + * + * @return the summaryCode value + */ + public String summaryCode() { + return this.summaryCode; + } + + /** + * Set the code of the health error. + * + * @param summaryCode the summaryCode value to set + * @return the HealthErrorSummary object itself. + */ + public HealthErrorSummary withSummaryCode(String summaryCode) { + this.summaryCode = summaryCode; + return this; + } + + /** + * Get the category of the health error. Possible values include: 'None', 'Replication', 'TestFailover', 'Configuration', 'FabricInfrastructure', 'VersionExpiry', 'AgentAutoUpdate'. + * + * @return the category value + */ + public HealthErrorCategory category() { + return this.category; + } + + /** + * Set the category of the health error. Possible values include: 'None', 'Replication', 'TestFailover', 'Configuration', 'FabricInfrastructure', 'VersionExpiry', 'AgentAutoUpdate'. + * + * @param category the category value to set + * @return the HealthErrorSummary object itself. + */ + public HealthErrorSummary withCategory(HealthErrorCategory category) { + this.category = category; + return this; + } + + /** + * Get severity of error. Possible values include: 'NONE', 'Warning', 'Error', 'Info'. + * + * @return the severity value + */ + public Severity severity() { + return this.severity; + } + + /** + * Set severity of error. Possible values include: 'NONE', 'Warning', 'Error', 'Info'. + * + * @param severity the severity value to set + * @return the HealthErrorSummary object itself. + */ + public HealthErrorSummary withSeverity(Severity severity) { + this.severity = severity; + return this; + } + + /** + * Get the summary message of the health error. + * + * @return the summaryMessage value + */ + public String summaryMessage() { + return this.summaryMessage; + } + + /** + * Set the summary message of the health error. + * + * @param summaryMessage the summaryMessage value to set + * @return the HealthErrorSummary object itself. + */ + public HealthErrorSummary withSummaryMessage(String summaryMessage) { + this.summaryMessage = summaryMessage; + return this; + } + + /** + * Get the type of affected ARM resource. + * + * @return the affectedResourceType value + */ + public String affectedResourceType() { + return this.affectedResourceType; + } + + /** + * Set the type of affected ARM resource. + * + * @param affectedResourceType the affectedResourceType value to set + * @return the HealthErrorSummary object itself. + */ + public HealthErrorSummary withAffectedResourceType(String affectedResourceType) { + this.affectedResourceType = affectedResourceType; + return this; + } + + /** + * Get the sub type of any subcomponent within the ARM resource that this might be applicable. Value remains null if not applicable. + * + * @return the affectedResourceSubtype value + */ + public String affectedResourceSubtype() { + return this.affectedResourceSubtype; + } + + /** + * Set the sub type of any subcomponent within the ARM resource that this might be applicable. Value remains null if not applicable. + * + * @param affectedResourceSubtype the affectedResourceSubtype value to set + * @return the HealthErrorSummary object itself. + */ + public HealthErrorSummary withAffectedResourceSubtype(String affectedResourceSubtype) { + this.affectedResourceSubtype = affectedResourceSubtype; + return this; + } + + /** + * Get the list of affected resource correlation Ids. This can be used to uniquely identify the count of items affected by a specific category and severity as well as count of item affected by an specific issue. + * + * @return the affectedResourceCorrelationIds value + */ + public List affectedResourceCorrelationIds() { + return this.affectedResourceCorrelationIds; + } + + /** + * Set the list of affected resource correlation Ids. This can be used to uniquely identify the count of items affected by a specific category and severity as well as count of item affected by an specific issue. + * + * @param affectedResourceCorrelationIds the affectedResourceCorrelationIds value to set + * @return the HealthErrorSummary object itself. + */ + public HealthErrorSummary withAffectedResourceCorrelationIds(List affectedResourceCorrelationIds) { + this.affectedResourceCorrelationIds = affectedResourceCorrelationIds; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplica2012EventDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplica2012EventDetails.java new file mode 100644 index 0000000000000..bde002947d04f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplica2012EventDetails.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Model class for event details of a HyperVReplica E2E event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplica2012") +public class HyperVReplica2012EventDetails extends EventProviderSpecificDetails { + /** + * The container friendly name. + */ + @JsonProperty(value = "containerName") + private String containerName; + + /** + * The fabric friendly name. + */ + @JsonProperty(value = "fabricName") + private String fabricName; + + /** + * The remote container name. + */ + @JsonProperty(value = "remoteContainerName") + private String remoteContainerName; + + /** + * The remote fabric name. + */ + @JsonProperty(value = "remoteFabricName") + private String remoteFabricName; + + /** + * Get the container friendly name. + * + * @return the containerName value + */ + public String containerName() { + return this.containerName; + } + + /** + * Set the container friendly name. + * + * @param containerName the containerName value to set + * @return the HyperVReplica2012EventDetails object itself. + */ + public HyperVReplica2012EventDetails withContainerName(String containerName) { + this.containerName = containerName; + return this; + } + + /** + * Get the fabric friendly name. + * + * @return the fabricName value + */ + public String fabricName() { + return this.fabricName; + } + + /** + * Set the fabric friendly name. + * + * @param fabricName the fabricName value to set + * @return the HyperVReplica2012EventDetails object itself. + */ + public HyperVReplica2012EventDetails withFabricName(String fabricName) { + this.fabricName = fabricName; + return this; + } + + /** + * Get the remote container name. + * + * @return the remoteContainerName value + */ + public String remoteContainerName() { + return this.remoteContainerName; + } + + /** + * Set the remote container name. + * + * @param remoteContainerName the remoteContainerName value to set + * @return the HyperVReplica2012EventDetails object itself. + */ + public HyperVReplica2012EventDetails withRemoteContainerName(String remoteContainerName) { + this.remoteContainerName = remoteContainerName; + return this; + } + + /** + * Get the remote fabric name. + * + * @return the remoteFabricName value + */ + public String remoteFabricName() { + return this.remoteFabricName; + } + + /** + * Set the remote fabric name. + * + * @param remoteFabricName the remoteFabricName value to set + * @return the HyperVReplica2012EventDetails object itself. + */ + public HyperVReplica2012EventDetails withRemoteFabricName(String remoteFabricName) { + this.remoteFabricName = remoteFabricName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplica2012R2EventDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplica2012R2EventDetails.java new file mode 100644 index 0000000000000..f1519f0a82ce8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplica2012R2EventDetails.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Model class for event details of a HyperVReplica blue E2E event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplica2012R2") +public class HyperVReplica2012R2EventDetails extends EventProviderSpecificDetails { + /** + * The container friendly name. + */ + @JsonProperty(value = "containerName") + private String containerName; + + /** + * The fabric friendly name. + */ + @JsonProperty(value = "fabricName") + private String fabricName; + + /** + * The remote container name. + */ + @JsonProperty(value = "remoteContainerName") + private String remoteContainerName; + + /** + * The remote fabric name. + */ + @JsonProperty(value = "remoteFabricName") + private String remoteFabricName; + + /** + * Get the container friendly name. + * + * @return the containerName value + */ + public String containerName() { + return this.containerName; + } + + /** + * Set the container friendly name. + * + * @param containerName the containerName value to set + * @return the HyperVReplica2012R2EventDetails object itself. + */ + public HyperVReplica2012R2EventDetails withContainerName(String containerName) { + this.containerName = containerName; + return this; + } + + /** + * Get the fabric friendly name. + * + * @return the fabricName value + */ + public String fabricName() { + return this.fabricName; + } + + /** + * Set the fabric friendly name. + * + * @param fabricName the fabricName value to set + * @return the HyperVReplica2012R2EventDetails object itself. + */ + public HyperVReplica2012R2EventDetails withFabricName(String fabricName) { + this.fabricName = fabricName; + return this; + } + + /** + * Get the remote container name. + * + * @return the remoteContainerName value + */ + public String remoteContainerName() { + return this.remoteContainerName; + } + + /** + * Set the remote container name. + * + * @param remoteContainerName the remoteContainerName value to set + * @return the HyperVReplica2012R2EventDetails object itself. + */ + public HyperVReplica2012R2EventDetails withRemoteContainerName(String remoteContainerName) { + this.remoteContainerName = remoteContainerName; + return this; + } + + /** + * Get the remote fabric name. + * + * @return the remoteFabricName value + */ + public String remoteFabricName() { + return this.remoteFabricName; + } + + /** + * Set the remote fabric name. + * + * @param remoteFabricName the remoteFabricName value to set + * @return the HyperVReplica2012R2EventDetails object itself. + */ + public HyperVReplica2012R2EventDetails withRemoteFabricName(String remoteFabricName) { + this.remoteFabricName = remoteFabricName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureApplyRecoveryPointInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureApplyRecoveryPointInput.java new file mode 100644 index 0000000000000..59de305a56969 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureApplyRecoveryPointInput.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * ApplyRecoveryPoint input specific to HyperVReplicaAzure provider. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzureApplyRecoveryPointInput extends ApplyRecoveryPointProviderSpecificInput { + /** + * The vault location where the recovery Vm resides. + */ + @JsonProperty(value = "vaultLocation") + private String vaultLocation; + + /** + * The primary kek certificate pfx. + */ + @JsonProperty(value = "primaryKekCertificatePfx") + private String primaryKekCertificatePfx; + + /** + * The secondary kek certificate pfx. + */ + @JsonProperty(value = "secondaryKekCertificatePfx") + private String secondaryKekCertificatePfx; + + /** + * Get the vault location where the recovery Vm resides. + * + * @return the vaultLocation value + */ + public String vaultLocation() { + return this.vaultLocation; + } + + /** + * Set the vault location where the recovery Vm resides. + * + * @param vaultLocation the vaultLocation value to set + * @return the HyperVReplicaAzureApplyRecoveryPointInput object itself. + */ + public HyperVReplicaAzureApplyRecoveryPointInput withVaultLocation(String vaultLocation) { + this.vaultLocation = vaultLocation; + return this; + } + + /** + * Get the primary kek certificate pfx. + * + * @return the primaryKekCertificatePfx value + */ + public String primaryKekCertificatePfx() { + return this.primaryKekCertificatePfx; + } + + /** + * Set the primary kek certificate pfx. + * + * @param primaryKekCertificatePfx the primaryKekCertificatePfx value to set + * @return the HyperVReplicaAzureApplyRecoveryPointInput object itself. + */ + public HyperVReplicaAzureApplyRecoveryPointInput withPrimaryKekCertificatePfx(String primaryKekCertificatePfx) { + this.primaryKekCertificatePfx = primaryKekCertificatePfx; + return this; + } + + /** + * Get the secondary kek certificate pfx. + * + * @return the secondaryKekCertificatePfx value + */ + public String secondaryKekCertificatePfx() { + return this.secondaryKekCertificatePfx; + } + + /** + * Set the secondary kek certificate pfx. + * + * @param secondaryKekCertificatePfx the secondaryKekCertificatePfx value to set + * @return the HyperVReplicaAzureApplyRecoveryPointInput object itself. + */ + public HyperVReplicaAzureApplyRecoveryPointInput withSecondaryKekCertificatePfx(String secondaryKekCertificatePfx) { + this.secondaryKekCertificatePfx = secondaryKekCertificatePfx; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureEnableProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureEnableProtectionInput.java new file mode 100644 index 0000000000000..1e31ba569cc00 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureEnableProtectionInput.java @@ -0,0 +1,389 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Azure specific enable protection input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzureEnableProtectionInput extends EnableProtectionProviderSpecificInput { + /** + * The Hyper-V host Vm Id. + */ + @JsonProperty(value = "hvHostVmId") + private String hvHostVmId; + + /** + * The Vm Name. + */ + @JsonProperty(value = "vmName") + private String vmName; + + /** + * The OS type associated with vm. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * The OS disk VHD id associated with vm. + */ + @JsonProperty(value = "vhdId") + private String vhdId; + + /** + * The storage account name. + */ + @JsonProperty(value = "targetStorageAccountId") + private String targetStorageAccountId; + + /** + * The selected target Azure network Id. + */ + @JsonProperty(value = "targetAzureNetworkId") + private String targetAzureNetworkId; + + /** + * The selected target Azure subnet Id. + */ + @JsonProperty(value = "targetAzureSubnetId") + private String targetAzureSubnetId; + + /** + * The selected option to enable RDP\SSH on target vm after failover. + * String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + */ + @JsonProperty(value = "enableRdpOnTargetOption") + private String enableRdpOnTargetOption; + + /** + * The target azure Vm Name. + */ + @JsonProperty(value = "targetAzureVmName") + private String targetAzureVmName; + + /** + * The storage account to be used for logging during replication. + */ + @JsonProperty(value = "logStorageAccountId") + private String logStorageAccountId; + + /** + * The list of VHD IDs of disks to be protected. + */ + @JsonProperty(value = "disksToInclude") + private List disksToInclude; + + /** + * The Id of the target resource group (for classic deployment) in which + * the failover VM is to be created. + */ + @JsonProperty(value = "targetAzureV1ResourceGroupId") + private String targetAzureV1ResourceGroupId; + + /** + * The Id of the target resource group (for resource manager deployment) in + * which the failover VM is to be created. + */ + @JsonProperty(value = "targetAzureV2ResourceGroupId") + private String targetAzureV2ResourceGroupId; + + /** + * A value indicating whether managed disks should be used during failover. + */ + @JsonProperty(value = "useManagedDisks") + private String useManagedDisks; + + /** + * Get the Hyper-V host Vm Id. + * + * @return the hvHostVmId value + */ + public String hvHostVmId() { + return this.hvHostVmId; + } + + /** + * Set the Hyper-V host Vm Id. + * + * @param hvHostVmId the hvHostVmId value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withHvHostVmId(String hvHostVmId) { + this.hvHostVmId = hvHostVmId; + return this; + } + + /** + * Get the Vm Name. + * + * @return the vmName value + */ + public String vmName() { + return this.vmName; + } + + /** + * Set the Vm Name. + * + * @param vmName the vmName value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withVmName(String vmName) { + this.vmName = vmName; + return this; + } + + /** + * Get the OS type associated with vm. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the OS type associated with vm. + * + * @param osType the osType value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get the OS disk VHD id associated with vm. + * + * @return the vhdId value + */ + public String vhdId() { + return this.vhdId; + } + + /** + * Set the OS disk VHD id associated with vm. + * + * @param vhdId the vhdId value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withVhdId(String vhdId) { + this.vhdId = vhdId; + return this; + } + + /** + * Get the storage account name. + * + * @return the targetStorageAccountId value + */ + public String targetStorageAccountId() { + return this.targetStorageAccountId; + } + + /** + * Set the storage account name. + * + * @param targetStorageAccountId the targetStorageAccountId value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withTargetStorageAccountId(String targetStorageAccountId) { + this.targetStorageAccountId = targetStorageAccountId; + return this; + } + + /** + * Get the selected target Azure network Id. + * + * @return the targetAzureNetworkId value + */ + public String targetAzureNetworkId() { + return this.targetAzureNetworkId; + } + + /** + * Set the selected target Azure network Id. + * + * @param targetAzureNetworkId the targetAzureNetworkId value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withTargetAzureNetworkId(String targetAzureNetworkId) { + this.targetAzureNetworkId = targetAzureNetworkId; + return this; + } + + /** + * Get the selected target Azure subnet Id. + * + * @return the targetAzureSubnetId value + */ + public String targetAzureSubnetId() { + return this.targetAzureSubnetId; + } + + /** + * Set the selected target Azure subnet Id. + * + * @param targetAzureSubnetId the targetAzureSubnetId value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withTargetAzureSubnetId(String targetAzureSubnetId) { + this.targetAzureSubnetId = targetAzureSubnetId; + return this; + } + + /** + * Get the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @return the enableRdpOnTargetOption value + */ + public String enableRdpOnTargetOption() { + return this.enableRdpOnTargetOption; + } + + /** + * Set the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @param enableRdpOnTargetOption the enableRdpOnTargetOption value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withEnableRdpOnTargetOption(String enableRdpOnTargetOption) { + this.enableRdpOnTargetOption = enableRdpOnTargetOption; + return this; + } + + /** + * Get the target azure Vm Name. + * + * @return the targetAzureVmName value + */ + public String targetAzureVmName() { + return this.targetAzureVmName; + } + + /** + * Set the target azure Vm Name. + * + * @param targetAzureVmName the targetAzureVmName value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withTargetAzureVmName(String targetAzureVmName) { + this.targetAzureVmName = targetAzureVmName; + return this; + } + + /** + * Get the storage account to be used for logging during replication. + * + * @return the logStorageAccountId value + */ + public String logStorageAccountId() { + return this.logStorageAccountId; + } + + /** + * Set the storage account to be used for logging during replication. + * + * @param logStorageAccountId the logStorageAccountId value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withLogStorageAccountId(String logStorageAccountId) { + this.logStorageAccountId = logStorageAccountId; + return this; + } + + /** + * Get the list of VHD IDs of disks to be protected. + * + * @return the disksToInclude value + */ + public List disksToInclude() { + return this.disksToInclude; + } + + /** + * Set the list of VHD IDs of disks to be protected. + * + * @param disksToInclude the disksToInclude value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withDisksToInclude(List disksToInclude) { + this.disksToInclude = disksToInclude; + return this; + } + + /** + * Get the Id of the target resource group (for classic deployment) in which the failover VM is to be created. + * + * @return the targetAzureV1ResourceGroupId value + */ + public String targetAzureV1ResourceGroupId() { + return this.targetAzureV1ResourceGroupId; + } + + /** + * Set the Id of the target resource group (for classic deployment) in which the failover VM is to be created. + * + * @param targetAzureV1ResourceGroupId the targetAzureV1ResourceGroupId value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withTargetAzureV1ResourceGroupId(String targetAzureV1ResourceGroupId) { + this.targetAzureV1ResourceGroupId = targetAzureV1ResourceGroupId; + return this; + } + + /** + * Get the Id of the target resource group (for resource manager deployment) in which the failover VM is to be created. + * + * @return the targetAzureV2ResourceGroupId value + */ + public String targetAzureV2ResourceGroupId() { + return this.targetAzureV2ResourceGroupId; + } + + /** + * Set the Id of the target resource group (for resource manager deployment) in which the failover VM is to be created. + * + * @param targetAzureV2ResourceGroupId the targetAzureV2ResourceGroupId value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withTargetAzureV2ResourceGroupId(String targetAzureV2ResourceGroupId) { + this.targetAzureV2ResourceGroupId = targetAzureV2ResourceGroupId; + return this; + } + + /** + * Get a value indicating whether managed disks should be used during failover. + * + * @return the useManagedDisks value + */ + public String useManagedDisks() { + return this.useManagedDisks; + } + + /** + * Set a value indicating whether managed disks should be used during failover. + * + * @param useManagedDisks the useManagedDisks value to set + * @return the HyperVReplicaAzureEnableProtectionInput object itself. + */ + public HyperVReplicaAzureEnableProtectionInput withUseManagedDisks(String useManagedDisks) { + this.useManagedDisks = useManagedDisks; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureEventDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureEventDetails.java new file mode 100644 index 0000000000000..dcf85b599fe4a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureEventDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Model class for event details of a HyperVReplica E2A event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzureEventDetails extends EventProviderSpecificDetails { + /** + * The container friendly name. + */ + @JsonProperty(value = "containerName") + private String containerName; + + /** + * The fabric friendly name. + */ + @JsonProperty(value = "fabricName") + private String fabricName; + + /** + * The remote container name. + */ + @JsonProperty(value = "remoteContainerName") + private String remoteContainerName; + + /** + * Get the container friendly name. + * + * @return the containerName value + */ + public String containerName() { + return this.containerName; + } + + /** + * Set the container friendly name. + * + * @param containerName the containerName value to set + * @return the HyperVReplicaAzureEventDetails object itself. + */ + public HyperVReplicaAzureEventDetails withContainerName(String containerName) { + this.containerName = containerName; + return this; + } + + /** + * Get the fabric friendly name. + * + * @return the fabricName value + */ + public String fabricName() { + return this.fabricName; + } + + /** + * Set the fabric friendly name. + * + * @param fabricName the fabricName value to set + * @return the HyperVReplicaAzureEventDetails object itself. + */ + public HyperVReplicaAzureEventDetails withFabricName(String fabricName) { + this.fabricName = fabricName; + return this; + } + + /** + * Get the remote container name. + * + * @return the remoteContainerName value + */ + public String remoteContainerName() { + return this.remoteContainerName; + } + + /** + * Set the remote container name. + * + * @param remoteContainerName the remoteContainerName value to set + * @return the HyperVReplicaAzureEventDetails object itself. + */ + public HyperVReplicaAzureEventDetails withRemoteContainerName(String remoteContainerName) { + this.remoteContainerName = remoteContainerName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureFailbackProviderInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureFailbackProviderInput.java new file mode 100644 index 0000000000000..5a6a362dd08f3 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureFailbackProviderInput.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * HvrA provider specific input for failback. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzureFailback") +public class HyperVReplicaAzureFailbackProviderInput extends ProviderSpecificFailoverInput { + /** + * Data sync option. + */ + @JsonProperty(value = "dataSyncOption") + private String dataSyncOption; + + /** + * ALR options to create alternate recovery. + */ + @JsonProperty(value = "recoveryVmCreationOption") + private String recoveryVmCreationOption; + + /** + * Provider ID for alternate location. + */ + @JsonProperty(value = "providerIdForAlternateRecovery") + private String providerIdForAlternateRecovery; + + /** + * Get data sync option. + * + * @return the dataSyncOption value + */ + public String dataSyncOption() { + return this.dataSyncOption; + } + + /** + * Set data sync option. + * + * @param dataSyncOption the dataSyncOption value to set + * @return the HyperVReplicaAzureFailbackProviderInput object itself. + */ + public HyperVReplicaAzureFailbackProviderInput withDataSyncOption(String dataSyncOption) { + this.dataSyncOption = dataSyncOption; + return this; + } + + /** + * Get aLR options to create alternate recovery. + * + * @return the recoveryVmCreationOption value + */ + public String recoveryVmCreationOption() { + return this.recoveryVmCreationOption; + } + + /** + * Set aLR options to create alternate recovery. + * + * @param recoveryVmCreationOption the recoveryVmCreationOption value to set + * @return the HyperVReplicaAzureFailbackProviderInput object itself. + */ + public HyperVReplicaAzureFailbackProviderInput withRecoveryVmCreationOption(String recoveryVmCreationOption) { + this.recoveryVmCreationOption = recoveryVmCreationOption; + return this; + } + + /** + * Get provider ID for alternate location. + * + * @return the providerIdForAlternateRecovery value + */ + public String providerIdForAlternateRecovery() { + return this.providerIdForAlternateRecovery; + } + + /** + * Set provider ID for alternate location. + * + * @param providerIdForAlternateRecovery the providerIdForAlternateRecovery value to set + * @return the HyperVReplicaAzureFailbackProviderInput object itself. + */ + public HyperVReplicaAzureFailbackProviderInput withProviderIdForAlternateRecovery(String providerIdForAlternateRecovery) { + this.providerIdForAlternateRecovery = providerIdForAlternateRecovery; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureFailoverProviderInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureFailoverProviderInput.java new file mode 100644 index 0000000000000..880bbe4dec174 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureFailoverProviderInput.java @@ -0,0 +1,126 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * HvrA provider specific input for failover. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzureFailoverProviderInput extends ProviderSpecificFailoverInput { + /** + * Location of the vault. + */ + @JsonProperty(value = "vaultLocation") + private String vaultLocation; + + /** + * Primary kek certificate pfx. + */ + @JsonProperty(value = "primaryKekCertificatePfx") + private String primaryKekCertificatePfx; + + /** + * Secondary kek certificate pfx. + */ + @JsonProperty(value = "secondaryKekCertificatePfx") + private String secondaryKekCertificatePfx; + + /** + * The recovery point id to be passed to failover to a particular recovery + * point. In case of latest recovery point, null should be passed. + */ + @JsonProperty(value = "recoveryPointId") + private String recoveryPointId; + + /** + * Get location of the vault. + * + * @return the vaultLocation value + */ + public String vaultLocation() { + return this.vaultLocation; + } + + /** + * Set location of the vault. + * + * @param vaultLocation the vaultLocation value to set + * @return the HyperVReplicaAzureFailoverProviderInput object itself. + */ + public HyperVReplicaAzureFailoverProviderInput withVaultLocation(String vaultLocation) { + this.vaultLocation = vaultLocation; + return this; + } + + /** + * Get primary kek certificate pfx. + * + * @return the primaryKekCertificatePfx value + */ + public String primaryKekCertificatePfx() { + return this.primaryKekCertificatePfx; + } + + /** + * Set primary kek certificate pfx. + * + * @param primaryKekCertificatePfx the primaryKekCertificatePfx value to set + * @return the HyperVReplicaAzureFailoverProviderInput object itself. + */ + public HyperVReplicaAzureFailoverProviderInput withPrimaryKekCertificatePfx(String primaryKekCertificatePfx) { + this.primaryKekCertificatePfx = primaryKekCertificatePfx; + return this; + } + + /** + * Get secondary kek certificate pfx. + * + * @return the secondaryKekCertificatePfx value + */ + public String secondaryKekCertificatePfx() { + return this.secondaryKekCertificatePfx; + } + + /** + * Set secondary kek certificate pfx. + * + * @param secondaryKekCertificatePfx the secondaryKekCertificatePfx value to set + * @return the HyperVReplicaAzureFailoverProviderInput object itself. + */ + public HyperVReplicaAzureFailoverProviderInput withSecondaryKekCertificatePfx(String secondaryKekCertificatePfx) { + this.secondaryKekCertificatePfx = secondaryKekCertificatePfx; + return this; + } + + /** + * Get the recovery point id to be passed to failover to a particular recovery point. In case of latest recovery point, null should be passed. + * + * @return the recoveryPointId value + */ + public String recoveryPointId() { + return this.recoveryPointId; + } + + /** + * Set the recovery point id to be passed to failover to a particular recovery point. In case of latest recovery point, null should be passed. + * + * @param recoveryPointId the recoveryPointId value to set + * @return the HyperVReplicaAzureFailoverProviderInput object itself. + */ + public HyperVReplicaAzureFailoverProviderInput withRecoveryPointId(String recoveryPointId) { + this.recoveryPointId = recoveryPointId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzurePolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzurePolicyDetails.java new file mode 100644 index 0000000000000..e5187c7f14c8b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzurePolicyDetails.java @@ -0,0 +1,181 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Hyper-V Replica Azure specific protection profile details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzurePolicyDetails extends PolicyProviderSpecificDetails { + /** + * The duration (in hours) to which point the recovery history needs to be + * maintained. + */ + @JsonProperty(value = "recoveryPointHistoryDurationInHours") + private Integer recoveryPointHistoryDurationInHours; + + /** + * The interval (in hours) at which Hyper-V Replica should create an + * application consistent snapshot within the VM. + */ + @JsonProperty(value = "applicationConsistentSnapshotFrequencyInHours") + private Integer applicationConsistentSnapshotFrequencyInHours; + + /** + * The replication interval. + */ + @JsonProperty(value = "replicationInterval") + private Integer replicationInterval; + + /** + * The scheduled start time for the initial replication. If this parameter + * is Null, the initial replication starts immediately. + */ + @JsonProperty(value = "onlineReplicationStartTime") + private String onlineReplicationStartTime; + + /** + * A value indicating whether encryption is enabled for virtual machines in + * this cloud. + */ + @JsonProperty(value = "encryption") + private String encryption; + + /** + * The active storage account Id. + */ + @JsonProperty(value = "activeStorageAccountId") + private String activeStorageAccountId; + + /** + * Get the duration (in hours) to which point the recovery history needs to be maintained. + * + * @return the recoveryPointHistoryDurationInHours value + */ + public Integer recoveryPointHistoryDurationInHours() { + return this.recoveryPointHistoryDurationInHours; + } + + /** + * Set the duration (in hours) to which point the recovery history needs to be maintained. + * + * @param recoveryPointHistoryDurationInHours the recoveryPointHistoryDurationInHours value to set + * @return the HyperVReplicaAzurePolicyDetails object itself. + */ + public HyperVReplicaAzurePolicyDetails withRecoveryPointHistoryDurationInHours(Integer recoveryPointHistoryDurationInHours) { + this.recoveryPointHistoryDurationInHours = recoveryPointHistoryDurationInHours; + return this; + } + + /** + * Get the interval (in hours) at which Hyper-V Replica should create an application consistent snapshot within the VM. + * + * @return the applicationConsistentSnapshotFrequencyInHours value + */ + public Integer applicationConsistentSnapshotFrequencyInHours() { + return this.applicationConsistentSnapshotFrequencyInHours; + } + + /** + * Set the interval (in hours) at which Hyper-V Replica should create an application consistent snapshot within the VM. + * + * @param applicationConsistentSnapshotFrequencyInHours the applicationConsistentSnapshotFrequencyInHours value to set + * @return the HyperVReplicaAzurePolicyDetails object itself. + */ + public HyperVReplicaAzurePolicyDetails withApplicationConsistentSnapshotFrequencyInHours(Integer applicationConsistentSnapshotFrequencyInHours) { + this.applicationConsistentSnapshotFrequencyInHours = applicationConsistentSnapshotFrequencyInHours; + return this; + } + + /** + * Get the replication interval. + * + * @return the replicationInterval value + */ + public Integer replicationInterval() { + return this.replicationInterval; + } + + /** + * Set the replication interval. + * + * @param replicationInterval the replicationInterval value to set + * @return the HyperVReplicaAzurePolicyDetails object itself. + */ + public HyperVReplicaAzurePolicyDetails withReplicationInterval(Integer replicationInterval) { + this.replicationInterval = replicationInterval; + return this; + } + + /** + * Get the scheduled start time for the initial replication. If this parameter is Null, the initial replication starts immediately. + * + * @return the onlineReplicationStartTime value + */ + public String onlineReplicationStartTime() { + return this.onlineReplicationStartTime; + } + + /** + * Set the scheduled start time for the initial replication. If this parameter is Null, the initial replication starts immediately. + * + * @param onlineReplicationStartTime the onlineReplicationStartTime value to set + * @return the HyperVReplicaAzurePolicyDetails object itself. + */ + public HyperVReplicaAzurePolicyDetails withOnlineReplicationStartTime(String onlineReplicationStartTime) { + this.onlineReplicationStartTime = onlineReplicationStartTime; + return this; + } + + /** + * Get a value indicating whether encryption is enabled for virtual machines in this cloud. + * + * @return the encryption value + */ + public String encryption() { + return this.encryption; + } + + /** + * Set a value indicating whether encryption is enabled for virtual machines in this cloud. + * + * @param encryption the encryption value to set + * @return the HyperVReplicaAzurePolicyDetails object itself. + */ + public HyperVReplicaAzurePolicyDetails withEncryption(String encryption) { + this.encryption = encryption; + return this; + } + + /** + * Get the active storage account Id. + * + * @return the activeStorageAccountId value + */ + public String activeStorageAccountId() { + return this.activeStorageAccountId; + } + + /** + * Set the active storage account Id. + * + * @param activeStorageAccountId the activeStorageAccountId value to set + * @return the HyperVReplicaAzurePolicyDetails object itself. + */ + public HyperVReplicaAzurePolicyDetails withActiveStorageAccountId(String activeStorageAccountId) { + this.activeStorageAccountId = activeStorageAccountId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzurePolicyInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzurePolicyInput.java new file mode 100644 index 0000000000000..de31d7a9c5a28 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzurePolicyInput.java @@ -0,0 +1,156 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Hyper-V Replica Azure specific input for creating a protection profile. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzurePolicyInput extends PolicyProviderSpecificInput { + /** + * The duration (in hours) to which point the recovery history needs to be + * maintained. + */ + @JsonProperty(value = "recoveryPointHistoryDuration") + private Integer recoveryPointHistoryDuration; + + /** + * The interval (in hours) at which Hyper-V Replica should create an + * application consistent snapshot within the VM. + */ + @JsonProperty(value = "applicationConsistentSnapshotFrequencyInHours") + private Integer applicationConsistentSnapshotFrequencyInHours; + + /** + * The replication interval. + */ + @JsonProperty(value = "replicationInterval") + private Integer replicationInterval; + + /** + * The scheduled start time for the initial replication. If this parameter + * is Null, the initial replication starts immediately. + */ + @JsonProperty(value = "onlineReplicationStartTime") + private String onlineReplicationStartTime; + + /** + * The list of storage accounts to which the VMs in the primary cloud can + * replicate to. + */ + @JsonProperty(value = "storageAccounts") + private List storageAccounts; + + /** + * Get the duration (in hours) to which point the recovery history needs to be maintained. + * + * @return the recoveryPointHistoryDuration value + */ + public Integer recoveryPointHistoryDuration() { + return this.recoveryPointHistoryDuration; + } + + /** + * Set the duration (in hours) to which point the recovery history needs to be maintained. + * + * @param recoveryPointHistoryDuration the recoveryPointHistoryDuration value to set + * @return the HyperVReplicaAzurePolicyInput object itself. + */ + public HyperVReplicaAzurePolicyInput withRecoveryPointHistoryDuration(Integer recoveryPointHistoryDuration) { + this.recoveryPointHistoryDuration = recoveryPointHistoryDuration; + return this; + } + + /** + * Get the interval (in hours) at which Hyper-V Replica should create an application consistent snapshot within the VM. + * + * @return the applicationConsistentSnapshotFrequencyInHours value + */ + public Integer applicationConsistentSnapshotFrequencyInHours() { + return this.applicationConsistentSnapshotFrequencyInHours; + } + + /** + * Set the interval (in hours) at which Hyper-V Replica should create an application consistent snapshot within the VM. + * + * @param applicationConsistentSnapshotFrequencyInHours the applicationConsistentSnapshotFrequencyInHours value to set + * @return the HyperVReplicaAzurePolicyInput object itself. + */ + public HyperVReplicaAzurePolicyInput withApplicationConsistentSnapshotFrequencyInHours(Integer applicationConsistentSnapshotFrequencyInHours) { + this.applicationConsistentSnapshotFrequencyInHours = applicationConsistentSnapshotFrequencyInHours; + return this; + } + + /** + * Get the replication interval. + * + * @return the replicationInterval value + */ + public Integer replicationInterval() { + return this.replicationInterval; + } + + /** + * Set the replication interval. + * + * @param replicationInterval the replicationInterval value to set + * @return the HyperVReplicaAzurePolicyInput object itself. + */ + public HyperVReplicaAzurePolicyInput withReplicationInterval(Integer replicationInterval) { + this.replicationInterval = replicationInterval; + return this; + } + + /** + * Get the scheduled start time for the initial replication. If this parameter is Null, the initial replication starts immediately. + * + * @return the onlineReplicationStartTime value + */ + public String onlineReplicationStartTime() { + return this.onlineReplicationStartTime; + } + + /** + * Set the scheduled start time for the initial replication. If this parameter is Null, the initial replication starts immediately. + * + * @param onlineReplicationStartTime the onlineReplicationStartTime value to set + * @return the HyperVReplicaAzurePolicyInput object itself. + */ + public HyperVReplicaAzurePolicyInput withOnlineReplicationStartTime(String onlineReplicationStartTime) { + this.onlineReplicationStartTime = onlineReplicationStartTime; + return this; + } + + /** + * Get the list of storage accounts to which the VMs in the primary cloud can replicate to. + * + * @return the storageAccounts value + */ + public List storageAccounts() { + return this.storageAccounts; + } + + /** + * Set the list of storage accounts to which the VMs in the primary cloud can replicate to. + * + * @param storageAccounts the storageAccounts value to set + * @return the HyperVReplicaAzurePolicyInput object itself. + */ + public HyperVReplicaAzurePolicyInput withStorageAccounts(List storageAccounts) { + this.storageAccounts = storageAccounts; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureReplicationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureReplicationDetails.java new file mode 100644 index 0000000000000..dd77e48a2c78d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureReplicationDetails.java @@ -0,0 +1,651 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Hyper V Replica Azure provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzureReplicationDetails extends ReplicationProviderSpecificSettings { + /** + * Azure VM Disk details. + */ + @JsonProperty(value = "azureVmDiskDetails") + private List azureVmDiskDetails; + + /** + * Recovery Azure given name. + */ + @JsonProperty(value = "recoveryAzureVmName") + private String recoveryAzureVmName; + + /** + * The Recovery Azure VM size. + */ + @JsonProperty(value = "recoveryAzureVMSize") + private String recoveryAzureVMSize; + + /** + * The recovery Azure storage account. + */ + @JsonProperty(value = "recoveryAzureStorageAccount") + private String recoveryAzureStorageAccount; + + /** + * The ARM id of the log storage account used for replication. This will be + * set to null if no log storage account was provided during enable + * protection. + */ + @JsonProperty(value = "recoveryAzureLogStorageAccountId") + private String recoveryAzureLogStorageAccountId; + + /** + * The Last replication time. + */ + @JsonProperty(value = "lastReplicatedTime") + private DateTime lastReplicatedTime; + + /** + * Last RPO value. + */ + @JsonProperty(value = "rpoInSeconds") + private Long rpoInSeconds; + + /** + * The last RPO calculated time. + */ + @JsonProperty(value = "lastRpoCalculatedTime") + private DateTime lastRpoCalculatedTime; + + /** + * The virtual machine Id. + */ + @JsonProperty(value = "vmId") + private String vmId; + + /** + * The protection state for the vm. + */ + @JsonProperty(value = "vmProtectionState") + private String vmProtectionState; + + /** + * The protection state description for the vm. + */ + @JsonProperty(value = "vmProtectionStateDescription") + private String vmProtectionStateDescription; + + /** + * Initial replication details. + */ + @JsonProperty(value = "initialReplicationDetails") + private InitialReplicationDetails initialReplicationDetails; + + /** + * The PE Network details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * The selected recovery azure network Id. + */ + @JsonProperty(value = "selectedRecoveryAzureNetworkId") + private String selectedRecoveryAzureNetworkId; + + /** + * The selected source nic Id which will be used as the primary nic during + * failover. + */ + @JsonProperty(value = "selectedSourceNicId") + private String selectedSourceNicId; + + /** + * The encryption info. + */ + @JsonProperty(value = "encryption") + private String encryption; + + /** + * The operating system info. + */ + @JsonProperty(value = "oSDetails") + private OSDetails oSDetails; + + /** + * The RAM size of the VM on the primary side. + */ + @JsonProperty(value = "sourceVmRamSizeInMB") + private Integer sourceVmRamSizeInMB; + + /** + * The CPU count of the VM on the primary side. + */ + @JsonProperty(value = "sourceVmCpuCount") + private Integer sourceVmCpuCount; + + /** + * The selected option to enable RDP\SSH on target vm after failover. + * String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + */ + @JsonProperty(value = "enableRdpOnTargetOption") + private String enableRdpOnTargetOption; + + /** + * The target resource group Id. + */ + @JsonProperty(value = "recoveryAzureResourceGroupId") + private String recoveryAzureResourceGroupId; + + /** + * The recovery availability set Id. + */ + @JsonProperty(value = "recoveryAvailabilitySetId") + private String recoveryAvailabilitySetId; + + /** + * A value indicating whether managed disks should be used during failover. + */ + @JsonProperty(value = "useManagedDisks") + private String useManagedDisks; + + /** + * License Type of the VM to be used. + */ + @JsonProperty(value = "licenseType") + private String licenseType; + + /** + * Get azure VM Disk details. + * + * @return the azureVmDiskDetails value + */ + public List azureVmDiskDetails() { + return this.azureVmDiskDetails; + } + + /** + * Set azure VM Disk details. + * + * @param azureVmDiskDetails the azureVmDiskDetails value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withAzureVmDiskDetails(List azureVmDiskDetails) { + this.azureVmDiskDetails = azureVmDiskDetails; + return this; + } + + /** + * Get recovery Azure given name. + * + * @return the recoveryAzureVmName value + */ + public String recoveryAzureVmName() { + return this.recoveryAzureVmName; + } + + /** + * Set recovery Azure given name. + * + * @param recoveryAzureVmName the recoveryAzureVmName value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withRecoveryAzureVmName(String recoveryAzureVmName) { + this.recoveryAzureVmName = recoveryAzureVmName; + return this; + } + + /** + * Get the Recovery Azure VM size. + * + * @return the recoveryAzureVMSize value + */ + public String recoveryAzureVMSize() { + return this.recoveryAzureVMSize; + } + + /** + * Set the Recovery Azure VM size. + * + * @param recoveryAzureVMSize the recoveryAzureVMSize value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withRecoveryAzureVMSize(String recoveryAzureVMSize) { + this.recoveryAzureVMSize = recoveryAzureVMSize; + return this; + } + + /** + * Get the recovery Azure storage account. + * + * @return the recoveryAzureStorageAccount value + */ + public String recoveryAzureStorageAccount() { + return this.recoveryAzureStorageAccount; + } + + /** + * Set the recovery Azure storage account. + * + * @param recoveryAzureStorageAccount the recoveryAzureStorageAccount value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withRecoveryAzureStorageAccount(String recoveryAzureStorageAccount) { + this.recoveryAzureStorageAccount = recoveryAzureStorageAccount; + return this; + } + + /** + * Get the ARM id of the log storage account used for replication. This will be set to null if no log storage account was provided during enable protection. + * + * @return the recoveryAzureLogStorageAccountId value + */ + public String recoveryAzureLogStorageAccountId() { + return this.recoveryAzureLogStorageAccountId; + } + + /** + * Set the ARM id of the log storage account used for replication. This will be set to null if no log storage account was provided during enable protection. + * + * @param recoveryAzureLogStorageAccountId the recoveryAzureLogStorageAccountId value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withRecoveryAzureLogStorageAccountId(String recoveryAzureLogStorageAccountId) { + this.recoveryAzureLogStorageAccountId = recoveryAzureLogStorageAccountId; + return this; + } + + /** + * Get the Last replication time. + * + * @return the lastReplicatedTime value + */ + public DateTime lastReplicatedTime() { + return this.lastReplicatedTime; + } + + /** + * Set the Last replication time. + * + * @param lastReplicatedTime the lastReplicatedTime value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withLastReplicatedTime(DateTime lastReplicatedTime) { + this.lastReplicatedTime = lastReplicatedTime; + return this; + } + + /** + * Get last RPO value. + * + * @return the rpoInSeconds value + */ + public Long rpoInSeconds() { + return this.rpoInSeconds; + } + + /** + * Set last RPO value. + * + * @param rpoInSeconds the rpoInSeconds value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withRpoInSeconds(Long rpoInSeconds) { + this.rpoInSeconds = rpoInSeconds; + return this; + } + + /** + * Get the last RPO calculated time. + * + * @return the lastRpoCalculatedTime value + */ + public DateTime lastRpoCalculatedTime() { + return this.lastRpoCalculatedTime; + } + + /** + * Set the last RPO calculated time. + * + * @param lastRpoCalculatedTime the lastRpoCalculatedTime value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withLastRpoCalculatedTime(DateTime lastRpoCalculatedTime) { + this.lastRpoCalculatedTime = lastRpoCalculatedTime; + return this; + } + + /** + * Get the virtual machine Id. + * + * @return the vmId value + */ + public String vmId() { + return this.vmId; + } + + /** + * Set the virtual machine Id. + * + * @param vmId the vmId value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withVmId(String vmId) { + this.vmId = vmId; + return this; + } + + /** + * Get the protection state for the vm. + * + * @return the vmProtectionState value + */ + public String vmProtectionState() { + return this.vmProtectionState; + } + + /** + * Set the protection state for the vm. + * + * @param vmProtectionState the vmProtectionState value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withVmProtectionState(String vmProtectionState) { + this.vmProtectionState = vmProtectionState; + return this; + } + + /** + * Get the protection state description for the vm. + * + * @return the vmProtectionStateDescription value + */ + public String vmProtectionStateDescription() { + return this.vmProtectionStateDescription; + } + + /** + * Set the protection state description for the vm. + * + * @param vmProtectionStateDescription the vmProtectionStateDescription value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withVmProtectionStateDescription(String vmProtectionStateDescription) { + this.vmProtectionStateDescription = vmProtectionStateDescription; + return this; + } + + /** + * Get initial replication details. + * + * @return the initialReplicationDetails value + */ + public InitialReplicationDetails initialReplicationDetails() { + return this.initialReplicationDetails; + } + + /** + * Set initial replication details. + * + * @param initialReplicationDetails the initialReplicationDetails value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withInitialReplicationDetails(InitialReplicationDetails initialReplicationDetails) { + this.initialReplicationDetails = initialReplicationDetails; + return this; + } + + /** + * Get the PE Network details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the PE Network details. + * + * @param vmNics the vmNics value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get the selected recovery azure network Id. + * + * @return the selectedRecoveryAzureNetworkId value + */ + public String selectedRecoveryAzureNetworkId() { + return this.selectedRecoveryAzureNetworkId; + } + + /** + * Set the selected recovery azure network Id. + * + * @param selectedRecoveryAzureNetworkId the selectedRecoveryAzureNetworkId value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withSelectedRecoveryAzureNetworkId(String selectedRecoveryAzureNetworkId) { + this.selectedRecoveryAzureNetworkId = selectedRecoveryAzureNetworkId; + return this; + } + + /** + * Get the selected source nic Id which will be used as the primary nic during failover. + * + * @return the selectedSourceNicId value + */ + public String selectedSourceNicId() { + return this.selectedSourceNicId; + } + + /** + * Set the selected source nic Id which will be used as the primary nic during failover. + * + * @param selectedSourceNicId the selectedSourceNicId value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withSelectedSourceNicId(String selectedSourceNicId) { + this.selectedSourceNicId = selectedSourceNicId; + return this; + } + + /** + * Get the encryption info. + * + * @return the encryption value + */ + public String encryption() { + return this.encryption; + } + + /** + * Set the encryption info. + * + * @param encryption the encryption value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withEncryption(String encryption) { + this.encryption = encryption; + return this; + } + + /** + * Get the operating system info. + * + * @return the oSDetails value + */ + public OSDetails oSDetails() { + return this.oSDetails; + } + + /** + * Set the operating system info. + * + * @param oSDetails the oSDetails value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withOSDetails(OSDetails oSDetails) { + this.oSDetails = oSDetails; + return this; + } + + /** + * Get the RAM size of the VM on the primary side. + * + * @return the sourceVmRamSizeInMB value + */ + public Integer sourceVmRamSizeInMB() { + return this.sourceVmRamSizeInMB; + } + + /** + * Set the RAM size of the VM on the primary side. + * + * @param sourceVmRamSizeInMB the sourceVmRamSizeInMB value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withSourceVmRamSizeInMB(Integer sourceVmRamSizeInMB) { + this.sourceVmRamSizeInMB = sourceVmRamSizeInMB; + return this; + } + + /** + * Get the CPU count of the VM on the primary side. + * + * @return the sourceVmCpuCount value + */ + public Integer sourceVmCpuCount() { + return this.sourceVmCpuCount; + } + + /** + * Set the CPU count of the VM on the primary side. + * + * @param sourceVmCpuCount the sourceVmCpuCount value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withSourceVmCpuCount(Integer sourceVmCpuCount) { + this.sourceVmCpuCount = sourceVmCpuCount; + return this; + } + + /** + * Get the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @return the enableRdpOnTargetOption value + */ + public String enableRdpOnTargetOption() { + return this.enableRdpOnTargetOption; + } + + /** + * Set the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @param enableRdpOnTargetOption the enableRdpOnTargetOption value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withEnableRdpOnTargetOption(String enableRdpOnTargetOption) { + this.enableRdpOnTargetOption = enableRdpOnTargetOption; + return this; + } + + /** + * Get the target resource group Id. + * + * @return the recoveryAzureResourceGroupId value + */ + public String recoveryAzureResourceGroupId() { + return this.recoveryAzureResourceGroupId; + } + + /** + * Set the target resource group Id. + * + * @param recoveryAzureResourceGroupId the recoveryAzureResourceGroupId value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withRecoveryAzureResourceGroupId(String recoveryAzureResourceGroupId) { + this.recoveryAzureResourceGroupId = recoveryAzureResourceGroupId; + return this; + } + + /** + * Get the recovery availability set Id. + * + * @return the recoveryAvailabilitySetId value + */ + public String recoveryAvailabilitySetId() { + return this.recoveryAvailabilitySetId; + } + + /** + * Set the recovery availability set Id. + * + * @param recoveryAvailabilitySetId the recoveryAvailabilitySetId value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withRecoveryAvailabilitySetId(String recoveryAvailabilitySetId) { + this.recoveryAvailabilitySetId = recoveryAvailabilitySetId; + return this; + } + + /** + * Get a value indicating whether managed disks should be used during failover. + * + * @return the useManagedDisks value + */ + public String useManagedDisks() { + return this.useManagedDisks; + } + + /** + * Set a value indicating whether managed disks should be used during failover. + * + * @param useManagedDisks the useManagedDisks value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withUseManagedDisks(String useManagedDisks) { + this.useManagedDisks = useManagedDisks; + return this; + } + + /** + * Get license Type of the VM to be used. + * + * @return the licenseType value + */ + public String licenseType() { + return this.licenseType; + } + + /** + * Set license Type of the VM to be used. + * + * @param licenseType the licenseType value to set + * @return the HyperVReplicaAzureReplicationDetails object itself. + */ + public HyperVReplicaAzureReplicationDetails withLicenseType(String licenseType) { + this.licenseType = licenseType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureReprotectInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureReprotectInput.java new file mode 100644 index 0000000000000..cb888b7f5f44f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureReprotectInput.java @@ -0,0 +1,177 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Azure specific reprotect input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzureReprotectInput extends ReverseReplicationProviderSpecificInput { + /** + * The Hyper-V host Vm Id. + */ + @JsonProperty(value = "hvHostVmId") + private String hvHostVmId; + + /** + * The Vm Name. + */ + @JsonProperty(value = "vmName") + private String vmName; + + /** + * The OS type associated with vm. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * The OS disk VHD id associated with vm. + */ + @JsonProperty(value = "vHDId") + private String vHDId; + + /** + * The storage account name. + */ + @JsonProperty(value = "storageAccountId") + private String storageAccountId; + + /** + * The storage account to be used for logging during replication. + */ + @JsonProperty(value = "logStorageAccountId") + private String logStorageAccountId; + + /** + * Get the Hyper-V host Vm Id. + * + * @return the hvHostVmId value + */ + public String hvHostVmId() { + return this.hvHostVmId; + } + + /** + * Set the Hyper-V host Vm Id. + * + * @param hvHostVmId the hvHostVmId value to set + * @return the HyperVReplicaAzureReprotectInput object itself. + */ + public HyperVReplicaAzureReprotectInput withHvHostVmId(String hvHostVmId) { + this.hvHostVmId = hvHostVmId; + return this; + } + + /** + * Get the Vm Name. + * + * @return the vmName value + */ + public String vmName() { + return this.vmName; + } + + /** + * Set the Vm Name. + * + * @param vmName the vmName value to set + * @return the HyperVReplicaAzureReprotectInput object itself. + */ + public HyperVReplicaAzureReprotectInput withVmName(String vmName) { + this.vmName = vmName; + return this; + } + + /** + * Get the OS type associated with vm. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the OS type associated with vm. + * + * @param osType the osType value to set + * @return the HyperVReplicaAzureReprotectInput object itself. + */ + public HyperVReplicaAzureReprotectInput withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get the OS disk VHD id associated with vm. + * + * @return the vHDId value + */ + public String vHDId() { + return this.vHDId; + } + + /** + * Set the OS disk VHD id associated with vm. + * + * @param vHDId the vHDId value to set + * @return the HyperVReplicaAzureReprotectInput object itself. + */ + public HyperVReplicaAzureReprotectInput withVHDId(String vHDId) { + this.vHDId = vHDId; + return this; + } + + /** + * Get the storage account name. + * + * @return the storageAccountId value + */ + public String storageAccountId() { + return this.storageAccountId; + } + + /** + * Set the storage account name. + * + * @param storageAccountId the storageAccountId value to set + * @return the HyperVReplicaAzureReprotectInput object itself. + */ + public HyperVReplicaAzureReprotectInput withStorageAccountId(String storageAccountId) { + this.storageAccountId = storageAccountId; + return this; + } + + /** + * Get the storage account to be used for logging during replication. + * + * @return the logStorageAccountId value + */ + public String logStorageAccountId() { + return this.logStorageAccountId; + } + + /** + * Set the storage account to be used for logging during replication. + * + * @param logStorageAccountId the logStorageAccountId value to set + * @return the HyperVReplicaAzureReprotectInput object itself. + */ + public HyperVReplicaAzureReprotectInput withLogStorageAccountId(String logStorageAccountId) { + this.logStorageAccountId = logStorageAccountId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureRpRecoveryPointType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureRpRecoveryPointType.java new file mode 100644 index 0000000000000..dfeb6ed3d1972 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureRpRecoveryPointType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for HyperVReplicaAzureRpRecoveryPointType. + */ +public final class HyperVReplicaAzureRpRecoveryPointType extends ExpandableStringEnum { + /** Static value Latest for HyperVReplicaAzureRpRecoveryPointType. */ + public static final HyperVReplicaAzureRpRecoveryPointType LATEST = fromString("Latest"); + + /** Static value LatestApplicationConsistent for HyperVReplicaAzureRpRecoveryPointType. */ + public static final HyperVReplicaAzureRpRecoveryPointType LATEST_APPLICATION_CONSISTENT = fromString("LatestApplicationConsistent"); + + /** Static value LatestProcessed for HyperVReplicaAzureRpRecoveryPointType. */ + public static final HyperVReplicaAzureRpRecoveryPointType LATEST_PROCESSED = fromString("LatestProcessed"); + + /** + * Creates or finds a HyperVReplicaAzureRpRecoveryPointType from its string representation. + * @param name a name to look for + * @return the corresponding HyperVReplicaAzureRpRecoveryPointType + */ + @JsonCreator + public static HyperVReplicaAzureRpRecoveryPointType fromString(String name) { + return fromString(name, HyperVReplicaAzureRpRecoveryPointType.class); + } + + /** + * @return known HyperVReplicaAzureRpRecoveryPointType values + */ + public static Collection values() { + return values(HyperVReplicaAzureRpRecoveryPointType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureUpdateReplicationProtectedItemInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureUpdateReplicationProtectedItemInput.java new file mode 100644 index 0000000000000..ee3295d99a74c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaAzureUpdateReplicationProtectedItemInput.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * HyperV replica Azure input to update replication protected item. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class HyperVReplicaAzureUpdateReplicationProtectedItemInput extends UpdateReplicationProtectedItemProviderInput { + /** + * The recovery Azure resource group Id for classic deployment. + */ + @JsonProperty(value = "recoveryAzureV1ResourceGroupId") + private String recoveryAzureV1ResourceGroupId; + + /** + * The recovery Azure resource group Id for resource manager deployment. + */ + @JsonProperty(value = "recoveryAzureV2ResourceGroupId") + private String recoveryAzureV2ResourceGroupId; + + /** + * A value indicating whether managed disks should be used during failover. + */ + @JsonProperty(value = "useManagedDisks") + private String useManagedDisks; + + /** + * Get the recovery Azure resource group Id for classic deployment. + * + * @return the recoveryAzureV1ResourceGroupId value + */ + public String recoveryAzureV1ResourceGroupId() { + return this.recoveryAzureV1ResourceGroupId; + } + + /** + * Set the recovery Azure resource group Id for classic deployment. + * + * @param recoveryAzureV1ResourceGroupId the recoveryAzureV1ResourceGroupId value to set + * @return the HyperVReplicaAzureUpdateReplicationProtectedItemInput object itself. + */ + public HyperVReplicaAzureUpdateReplicationProtectedItemInput withRecoveryAzureV1ResourceGroupId(String recoveryAzureV1ResourceGroupId) { + this.recoveryAzureV1ResourceGroupId = recoveryAzureV1ResourceGroupId; + return this; + } + + /** + * Get the recovery Azure resource group Id for resource manager deployment. + * + * @return the recoveryAzureV2ResourceGroupId value + */ + public String recoveryAzureV2ResourceGroupId() { + return this.recoveryAzureV2ResourceGroupId; + } + + /** + * Set the recovery Azure resource group Id for resource manager deployment. + * + * @param recoveryAzureV2ResourceGroupId the recoveryAzureV2ResourceGroupId value to set + * @return the HyperVReplicaAzureUpdateReplicationProtectedItemInput object itself. + */ + public HyperVReplicaAzureUpdateReplicationProtectedItemInput withRecoveryAzureV2ResourceGroupId(String recoveryAzureV2ResourceGroupId) { + this.recoveryAzureV2ResourceGroupId = recoveryAzureV2ResourceGroupId; + return this; + } + + /** + * Get a value indicating whether managed disks should be used during failover. + * + * @return the useManagedDisks value + */ + public String useManagedDisks() { + return this.useManagedDisks; + } + + /** + * Set a value indicating whether managed disks should be used during failover. + * + * @param useManagedDisks the useManagedDisks value to set + * @return the HyperVReplicaAzureUpdateReplicationProtectedItemInput object itself. + */ + public HyperVReplicaAzureUpdateReplicationProtectedItemInput withUseManagedDisks(String useManagedDisks) { + this.useManagedDisks = useManagedDisks; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBaseEventDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBaseEventDetails.java new file mode 100644 index 0000000000000..200f5903d6cb7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBaseEventDetails.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Abstract model class for event details of a HyperVReplica E2E event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaBaseEventDetails") +public class HyperVReplicaBaseEventDetails extends EventProviderSpecificDetails { + /** + * The container friendly name. + */ + @JsonProperty(value = "containerName") + private String containerName; + + /** + * The fabric friendly name. + */ + @JsonProperty(value = "fabricName") + private String fabricName; + + /** + * The remote container name. + */ + @JsonProperty(value = "remoteContainerName") + private String remoteContainerName; + + /** + * The remote fabric name. + */ + @JsonProperty(value = "remoteFabricName") + private String remoteFabricName; + + /** + * Get the container friendly name. + * + * @return the containerName value + */ + public String containerName() { + return this.containerName; + } + + /** + * Set the container friendly name. + * + * @param containerName the containerName value to set + * @return the HyperVReplicaBaseEventDetails object itself. + */ + public HyperVReplicaBaseEventDetails withContainerName(String containerName) { + this.containerName = containerName; + return this; + } + + /** + * Get the fabric friendly name. + * + * @return the fabricName value + */ + public String fabricName() { + return this.fabricName; + } + + /** + * Set the fabric friendly name. + * + * @param fabricName the fabricName value to set + * @return the HyperVReplicaBaseEventDetails object itself. + */ + public HyperVReplicaBaseEventDetails withFabricName(String fabricName) { + this.fabricName = fabricName; + return this; + } + + /** + * Get the remote container name. + * + * @return the remoteContainerName value + */ + public String remoteContainerName() { + return this.remoteContainerName; + } + + /** + * Set the remote container name. + * + * @param remoteContainerName the remoteContainerName value to set + * @return the HyperVReplicaBaseEventDetails object itself. + */ + public HyperVReplicaBaseEventDetails withRemoteContainerName(String remoteContainerName) { + this.remoteContainerName = remoteContainerName; + return this; + } + + /** + * Get the remote fabric name. + * + * @return the remoteFabricName value + */ + public String remoteFabricName() { + return this.remoteFabricName; + } + + /** + * Set the remote fabric name. + * + * @param remoteFabricName the remoteFabricName value to set + * @return the HyperVReplicaBaseEventDetails object itself. + */ + public HyperVReplicaBaseEventDetails withRemoteFabricName(String remoteFabricName) { + this.remoteFabricName = remoteFabricName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBasePolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBasePolicyDetails.java new file mode 100644 index 0000000000000..2828de2490601 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBasePolicyDetails.java @@ -0,0 +1,282 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Base class for HyperVReplica policy details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaBasePolicyDetails") +public class HyperVReplicaBasePolicyDetails extends PolicyProviderSpecificDetails { + /** + * A value indicating the number of recovery points. + */ + @JsonProperty(value = "recoveryPoints") + private Integer recoveryPoints; + + /** + * A value indicating the application consistent frequency. + */ + @JsonProperty(value = "applicationConsistentSnapshotFrequencyInHours") + private Integer applicationConsistentSnapshotFrequencyInHours; + + /** + * A value indicating whether compression has to be enabled. + */ + @JsonProperty(value = "compression") + private String compression; + + /** + * A value indicating whether IR is online. + */ + @JsonProperty(value = "initialReplicationMethod") + private String initialReplicationMethod; + + /** + * A value indicating the online IR start time. + */ + @JsonProperty(value = "onlineReplicationStartTime") + private String onlineReplicationStartTime; + + /** + * A value indicating the offline IR import path. + */ + @JsonProperty(value = "offlineReplicationImportPath") + private String offlineReplicationImportPath; + + /** + * A value indicating the offline IR export path. + */ + @JsonProperty(value = "offlineReplicationExportPath") + private String offlineReplicationExportPath; + + /** + * A value indicating the recovery HTTPS port. + */ + @JsonProperty(value = "replicationPort") + private Integer replicationPort; + + /** + * A value indicating the authentication type. + */ + @JsonProperty(value = "allowedAuthenticationType") + private Integer allowedAuthenticationType; + + /** + * A value indicating whether the VM has to be auto deleted. Supported + * Values: String.Empty, None, OnRecoveryCloud. + */ + @JsonProperty(value = "replicaDeletionOption") + private String replicaDeletionOption; + + /** + * Get a value indicating the number of recovery points. + * + * @return the recoveryPoints value + */ + public Integer recoveryPoints() { + return this.recoveryPoints; + } + + /** + * Set a value indicating the number of recovery points. + * + * @param recoveryPoints the recoveryPoints value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withRecoveryPoints(Integer recoveryPoints) { + this.recoveryPoints = recoveryPoints; + return this; + } + + /** + * Get a value indicating the application consistent frequency. + * + * @return the applicationConsistentSnapshotFrequencyInHours value + */ + public Integer applicationConsistentSnapshotFrequencyInHours() { + return this.applicationConsistentSnapshotFrequencyInHours; + } + + /** + * Set a value indicating the application consistent frequency. + * + * @param applicationConsistentSnapshotFrequencyInHours the applicationConsistentSnapshotFrequencyInHours value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withApplicationConsistentSnapshotFrequencyInHours(Integer applicationConsistentSnapshotFrequencyInHours) { + this.applicationConsistentSnapshotFrequencyInHours = applicationConsistentSnapshotFrequencyInHours; + return this; + } + + /** + * Get a value indicating whether compression has to be enabled. + * + * @return the compression value + */ + public String compression() { + return this.compression; + } + + /** + * Set a value indicating whether compression has to be enabled. + * + * @param compression the compression value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Get a value indicating whether IR is online. + * + * @return the initialReplicationMethod value + */ + public String initialReplicationMethod() { + return this.initialReplicationMethod; + } + + /** + * Set a value indicating whether IR is online. + * + * @param initialReplicationMethod the initialReplicationMethod value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withInitialReplicationMethod(String initialReplicationMethod) { + this.initialReplicationMethod = initialReplicationMethod; + return this; + } + + /** + * Get a value indicating the online IR start time. + * + * @return the onlineReplicationStartTime value + */ + public String onlineReplicationStartTime() { + return this.onlineReplicationStartTime; + } + + /** + * Set a value indicating the online IR start time. + * + * @param onlineReplicationStartTime the onlineReplicationStartTime value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withOnlineReplicationStartTime(String onlineReplicationStartTime) { + this.onlineReplicationStartTime = onlineReplicationStartTime; + return this; + } + + /** + * Get a value indicating the offline IR import path. + * + * @return the offlineReplicationImportPath value + */ + public String offlineReplicationImportPath() { + return this.offlineReplicationImportPath; + } + + /** + * Set a value indicating the offline IR import path. + * + * @param offlineReplicationImportPath the offlineReplicationImportPath value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withOfflineReplicationImportPath(String offlineReplicationImportPath) { + this.offlineReplicationImportPath = offlineReplicationImportPath; + return this; + } + + /** + * Get a value indicating the offline IR export path. + * + * @return the offlineReplicationExportPath value + */ + public String offlineReplicationExportPath() { + return this.offlineReplicationExportPath; + } + + /** + * Set a value indicating the offline IR export path. + * + * @param offlineReplicationExportPath the offlineReplicationExportPath value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withOfflineReplicationExportPath(String offlineReplicationExportPath) { + this.offlineReplicationExportPath = offlineReplicationExportPath; + return this; + } + + /** + * Get a value indicating the recovery HTTPS port. + * + * @return the replicationPort value + */ + public Integer replicationPort() { + return this.replicationPort; + } + + /** + * Set a value indicating the recovery HTTPS port. + * + * @param replicationPort the replicationPort value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withReplicationPort(Integer replicationPort) { + this.replicationPort = replicationPort; + return this; + } + + /** + * Get a value indicating the authentication type. + * + * @return the allowedAuthenticationType value + */ + public Integer allowedAuthenticationType() { + return this.allowedAuthenticationType; + } + + /** + * Set a value indicating the authentication type. + * + * @param allowedAuthenticationType the allowedAuthenticationType value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withAllowedAuthenticationType(Integer allowedAuthenticationType) { + this.allowedAuthenticationType = allowedAuthenticationType; + return this; + } + + /** + * Get a value indicating whether the VM has to be auto deleted. Supported Values: String.Empty, None, OnRecoveryCloud. + * + * @return the replicaDeletionOption value + */ + public String replicaDeletionOption() { + return this.replicaDeletionOption; + } + + /** + * Set a value indicating whether the VM has to be auto deleted. Supported Values: String.Empty, None, OnRecoveryCloud. + * + * @param replicaDeletionOption the replicaDeletionOption value to set + * @return the HyperVReplicaBasePolicyDetails object itself. + */ + public HyperVReplicaBasePolicyDetails withReplicaDeletionOption(String replicaDeletionOption) { + this.replicaDeletionOption = replicaDeletionOption; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBaseReplicationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBaseReplicationDetails.java new file mode 100644 index 0000000000000..b80d066a6719d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBaseReplicationDetails.java @@ -0,0 +1,205 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Hyper V replica provider specific settings base class. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaBaseReplicationDetails") +public class HyperVReplicaBaseReplicationDetails extends ReplicationProviderSpecificSettings { + /** + * The Last replication time. + */ + @JsonProperty(value = "lastReplicatedTime") + private DateTime lastReplicatedTime; + + /** + * The PE Network details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * The virtual machine Id. + */ + @JsonProperty(value = "vmId") + private String vmId; + + /** + * The protection state for the vm. + */ + @JsonProperty(value = "vmProtectionState") + private String vmProtectionState; + + /** + * The protection state description for the vm. + */ + @JsonProperty(value = "vmProtectionStateDescription") + private String vmProtectionStateDescription; + + /** + * Initial replication details. + */ + @JsonProperty(value = "initialReplicationDetails") + private InitialReplicationDetails initialReplicationDetails; + + /** + * VM disk details. + */ + @JsonProperty(value = "vMDiskDetails") + private List vMDiskDetails; + + /** + * Get the Last replication time. + * + * @return the lastReplicatedTime value + */ + public DateTime lastReplicatedTime() { + return this.lastReplicatedTime; + } + + /** + * Set the Last replication time. + * + * @param lastReplicatedTime the lastReplicatedTime value to set + * @return the HyperVReplicaBaseReplicationDetails object itself. + */ + public HyperVReplicaBaseReplicationDetails withLastReplicatedTime(DateTime lastReplicatedTime) { + this.lastReplicatedTime = lastReplicatedTime; + return this; + } + + /** + * Get the PE Network details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the PE Network details. + * + * @param vmNics the vmNics value to set + * @return the HyperVReplicaBaseReplicationDetails object itself. + */ + public HyperVReplicaBaseReplicationDetails withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get the virtual machine Id. + * + * @return the vmId value + */ + public String vmId() { + return this.vmId; + } + + /** + * Set the virtual machine Id. + * + * @param vmId the vmId value to set + * @return the HyperVReplicaBaseReplicationDetails object itself. + */ + public HyperVReplicaBaseReplicationDetails withVmId(String vmId) { + this.vmId = vmId; + return this; + } + + /** + * Get the protection state for the vm. + * + * @return the vmProtectionState value + */ + public String vmProtectionState() { + return this.vmProtectionState; + } + + /** + * Set the protection state for the vm. + * + * @param vmProtectionState the vmProtectionState value to set + * @return the HyperVReplicaBaseReplicationDetails object itself. + */ + public HyperVReplicaBaseReplicationDetails withVmProtectionState(String vmProtectionState) { + this.vmProtectionState = vmProtectionState; + return this; + } + + /** + * Get the protection state description for the vm. + * + * @return the vmProtectionStateDescription value + */ + public String vmProtectionStateDescription() { + return this.vmProtectionStateDescription; + } + + /** + * Set the protection state description for the vm. + * + * @param vmProtectionStateDescription the vmProtectionStateDescription value to set + * @return the HyperVReplicaBaseReplicationDetails object itself. + */ + public HyperVReplicaBaseReplicationDetails withVmProtectionStateDescription(String vmProtectionStateDescription) { + this.vmProtectionStateDescription = vmProtectionStateDescription; + return this; + } + + /** + * Get initial replication details. + * + * @return the initialReplicationDetails value + */ + public InitialReplicationDetails initialReplicationDetails() { + return this.initialReplicationDetails; + } + + /** + * Set initial replication details. + * + * @param initialReplicationDetails the initialReplicationDetails value to set + * @return the HyperVReplicaBaseReplicationDetails object itself. + */ + public HyperVReplicaBaseReplicationDetails withInitialReplicationDetails(InitialReplicationDetails initialReplicationDetails) { + this.initialReplicationDetails = initialReplicationDetails; + return this; + } + + /** + * Get vM disk details. + * + * @return the vMDiskDetails value + */ + public List vMDiskDetails() { + return this.vMDiskDetails; + } + + /** + * Set vM disk details. + * + * @param vMDiskDetails the vMDiskDetails value to set + * @return the HyperVReplicaBaseReplicationDetails object itself. + */ + public HyperVReplicaBaseReplicationDetails withVMDiskDetails(List vMDiskDetails) { + this.vMDiskDetails = vMDiskDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBluePolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBluePolicyDetails.java new file mode 100644 index 0000000000000..15b8b1fdfd6a3 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBluePolicyDetails.java @@ -0,0 +1,308 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Hyper-V Replica Blue specific protection profile details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplica2012R2") +public class HyperVReplicaBluePolicyDetails extends PolicyProviderSpecificDetails { + /** + * A value indicating the replication interval. + */ + @JsonProperty(value = "replicationFrequencyInSeconds") + private Integer replicationFrequencyInSeconds; + + /** + * A value indicating the number of recovery points. + */ + @JsonProperty(value = "recoveryPoints") + private Integer recoveryPoints; + + /** + * A value indicating the application consistent frequency. + */ + @JsonProperty(value = "applicationConsistentSnapshotFrequencyInHours") + private Integer applicationConsistentSnapshotFrequencyInHours; + + /** + * A value indicating whether compression has to be enabled. + */ + @JsonProperty(value = "compression") + private String compression; + + /** + * A value indicating whether IR is online. + */ + @JsonProperty(value = "initialReplicationMethod") + private String initialReplicationMethod; + + /** + * A value indicating the online IR start time. + */ + @JsonProperty(value = "onlineReplicationStartTime") + private String onlineReplicationStartTime; + + /** + * A value indicating the offline IR import path. + */ + @JsonProperty(value = "offlineReplicationImportPath") + private String offlineReplicationImportPath; + + /** + * A value indicating the offline IR export path. + */ + @JsonProperty(value = "offlineReplicationExportPath") + private String offlineReplicationExportPath; + + /** + * A value indicating the recovery HTTPS port. + */ + @JsonProperty(value = "replicationPort") + private Integer replicationPort; + + /** + * A value indicating the authentication type. + */ + @JsonProperty(value = "allowedAuthenticationType") + private Integer allowedAuthenticationType; + + /** + * A value indicating whether the VM has to be auto deleted. Supported + * Values: String.Empty, None, OnRecoveryCloud. + */ + @JsonProperty(value = "replicaDeletionOption") + private String replicaDeletionOption; + + /** + * Get a value indicating the replication interval. + * + * @return the replicationFrequencyInSeconds value + */ + public Integer replicationFrequencyInSeconds() { + return this.replicationFrequencyInSeconds; + } + + /** + * Set a value indicating the replication interval. + * + * @param replicationFrequencyInSeconds the replicationFrequencyInSeconds value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withReplicationFrequencyInSeconds(Integer replicationFrequencyInSeconds) { + this.replicationFrequencyInSeconds = replicationFrequencyInSeconds; + return this; + } + + /** + * Get a value indicating the number of recovery points. + * + * @return the recoveryPoints value + */ + public Integer recoveryPoints() { + return this.recoveryPoints; + } + + /** + * Set a value indicating the number of recovery points. + * + * @param recoveryPoints the recoveryPoints value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withRecoveryPoints(Integer recoveryPoints) { + this.recoveryPoints = recoveryPoints; + return this; + } + + /** + * Get a value indicating the application consistent frequency. + * + * @return the applicationConsistentSnapshotFrequencyInHours value + */ + public Integer applicationConsistentSnapshotFrequencyInHours() { + return this.applicationConsistentSnapshotFrequencyInHours; + } + + /** + * Set a value indicating the application consistent frequency. + * + * @param applicationConsistentSnapshotFrequencyInHours the applicationConsistentSnapshotFrequencyInHours value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withApplicationConsistentSnapshotFrequencyInHours(Integer applicationConsistentSnapshotFrequencyInHours) { + this.applicationConsistentSnapshotFrequencyInHours = applicationConsistentSnapshotFrequencyInHours; + return this; + } + + /** + * Get a value indicating whether compression has to be enabled. + * + * @return the compression value + */ + public String compression() { + return this.compression; + } + + /** + * Set a value indicating whether compression has to be enabled. + * + * @param compression the compression value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Get a value indicating whether IR is online. + * + * @return the initialReplicationMethod value + */ + public String initialReplicationMethod() { + return this.initialReplicationMethod; + } + + /** + * Set a value indicating whether IR is online. + * + * @param initialReplicationMethod the initialReplicationMethod value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withInitialReplicationMethod(String initialReplicationMethod) { + this.initialReplicationMethod = initialReplicationMethod; + return this; + } + + /** + * Get a value indicating the online IR start time. + * + * @return the onlineReplicationStartTime value + */ + public String onlineReplicationStartTime() { + return this.onlineReplicationStartTime; + } + + /** + * Set a value indicating the online IR start time. + * + * @param onlineReplicationStartTime the onlineReplicationStartTime value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withOnlineReplicationStartTime(String onlineReplicationStartTime) { + this.onlineReplicationStartTime = onlineReplicationStartTime; + return this; + } + + /** + * Get a value indicating the offline IR import path. + * + * @return the offlineReplicationImportPath value + */ + public String offlineReplicationImportPath() { + return this.offlineReplicationImportPath; + } + + /** + * Set a value indicating the offline IR import path. + * + * @param offlineReplicationImportPath the offlineReplicationImportPath value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withOfflineReplicationImportPath(String offlineReplicationImportPath) { + this.offlineReplicationImportPath = offlineReplicationImportPath; + return this; + } + + /** + * Get a value indicating the offline IR export path. + * + * @return the offlineReplicationExportPath value + */ + public String offlineReplicationExportPath() { + return this.offlineReplicationExportPath; + } + + /** + * Set a value indicating the offline IR export path. + * + * @param offlineReplicationExportPath the offlineReplicationExportPath value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withOfflineReplicationExportPath(String offlineReplicationExportPath) { + this.offlineReplicationExportPath = offlineReplicationExportPath; + return this; + } + + /** + * Get a value indicating the recovery HTTPS port. + * + * @return the replicationPort value + */ + public Integer replicationPort() { + return this.replicationPort; + } + + /** + * Set a value indicating the recovery HTTPS port. + * + * @param replicationPort the replicationPort value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withReplicationPort(Integer replicationPort) { + this.replicationPort = replicationPort; + return this; + } + + /** + * Get a value indicating the authentication type. + * + * @return the allowedAuthenticationType value + */ + public Integer allowedAuthenticationType() { + return this.allowedAuthenticationType; + } + + /** + * Set a value indicating the authentication type. + * + * @param allowedAuthenticationType the allowedAuthenticationType value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withAllowedAuthenticationType(Integer allowedAuthenticationType) { + this.allowedAuthenticationType = allowedAuthenticationType; + return this; + } + + /** + * Get a value indicating whether the VM has to be auto deleted. Supported Values: String.Empty, None, OnRecoveryCloud. + * + * @return the replicaDeletionOption value + */ + public String replicaDeletionOption() { + return this.replicaDeletionOption; + } + + /** + * Set a value indicating whether the VM has to be auto deleted. Supported Values: String.Empty, None, OnRecoveryCloud. + * + * @param replicaDeletionOption the replicaDeletionOption value to set + * @return the HyperVReplicaBluePolicyDetails object itself. + */ + public HyperVReplicaBluePolicyDetails withReplicaDeletionOption(String replicaDeletionOption) { + this.replicaDeletionOption = replicaDeletionOption; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBluePolicyInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBluePolicyInput.java new file mode 100644 index 0000000000000..f491978500bc7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBluePolicyInput.java @@ -0,0 +1,307 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * HyperV Replica Blue policy input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplica2012R2") +public class HyperVReplicaBluePolicyInput extends PolicyProviderSpecificInput { + /** + * A value indicating the replication interval. + */ + @JsonProperty(value = "replicationFrequencyInSeconds") + private Integer replicationFrequencyInSeconds; + + /** + * A value indicating the number of recovery points. + */ + @JsonProperty(value = "recoveryPoints") + private Integer recoveryPoints; + + /** + * A value indicating the application consistent frequency. + */ + @JsonProperty(value = "applicationConsistentSnapshotFrequencyInHours") + private Integer applicationConsistentSnapshotFrequencyInHours; + + /** + * A value indicating whether compression has to be enabled. + */ + @JsonProperty(value = "compression") + private String compression; + + /** + * A value indicating whether IR is online. + */ + @JsonProperty(value = "initialReplicationMethod") + private String initialReplicationMethod; + + /** + * A value indicating the online IR start time. + */ + @JsonProperty(value = "onlineReplicationStartTime") + private String onlineReplicationStartTime; + + /** + * A value indicating the offline IR import path. + */ + @JsonProperty(value = "offlineReplicationImportPath") + private String offlineReplicationImportPath; + + /** + * A value indicating the offline IR export path. + */ + @JsonProperty(value = "offlineReplicationExportPath") + private String offlineReplicationExportPath; + + /** + * A value indicating the recovery HTTPS port. + */ + @JsonProperty(value = "replicationPort") + private Integer replicationPort; + + /** + * A value indicating the authentication type. + */ + @JsonProperty(value = "allowedAuthenticationType") + private Integer allowedAuthenticationType; + + /** + * A value indicating whether the VM has to be auto deleted. + */ + @JsonProperty(value = "replicaDeletion") + private String replicaDeletion; + + /** + * Get a value indicating the replication interval. + * + * @return the replicationFrequencyInSeconds value + */ + public Integer replicationFrequencyInSeconds() { + return this.replicationFrequencyInSeconds; + } + + /** + * Set a value indicating the replication interval. + * + * @param replicationFrequencyInSeconds the replicationFrequencyInSeconds value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withReplicationFrequencyInSeconds(Integer replicationFrequencyInSeconds) { + this.replicationFrequencyInSeconds = replicationFrequencyInSeconds; + return this; + } + + /** + * Get a value indicating the number of recovery points. + * + * @return the recoveryPoints value + */ + public Integer recoveryPoints() { + return this.recoveryPoints; + } + + /** + * Set a value indicating the number of recovery points. + * + * @param recoveryPoints the recoveryPoints value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withRecoveryPoints(Integer recoveryPoints) { + this.recoveryPoints = recoveryPoints; + return this; + } + + /** + * Get a value indicating the application consistent frequency. + * + * @return the applicationConsistentSnapshotFrequencyInHours value + */ + public Integer applicationConsistentSnapshotFrequencyInHours() { + return this.applicationConsistentSnapshotFrequencyInHours; + } + + /** + * Set a value indicating the application consistent frequency. + * + * @param applicationConsistentSnapshotFrequencyInHours the applicationConsistentSnapshotFrequencyInHours value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withApplicationConsistentSnapshotFrequencyInHours(Integer applicationConsistentSnapshotFrequencyInHours) { + this.applicationConsistentSnapshotFrequencyInHours = applicationConsistentSnapshotFrequencyInHours; + return this; + } + + /** + * Get a value indicating whether compression has to be enabled. + * + * @return the compression value + */ + public String compression() { + return this.compression; + } + + /** + * Set a value indicating whether compression has to be enabled. + * + * @param compression the compression value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Get a value indicating whether IR is online. + * + * @return the initialReplicationMethod value + */ + public String initialReplicationMethod() { + return this.initialReplicationMethod; + } + + /** + * Set a value indicating whether IR is online. + * + * @param initialReplicationMethod the initialReplicationMethod value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withInitialReplicationMethod(String initialReplicationMethod) { + this.initialReplicationMethod = initialReplicationMethod; + return this; + } + + /** + * Get a value indicating the online IR start time. + * + * @return the onlineReplicationStartTime value + */ + public String onlineReplicationStartTime() { + return this.onlineReplicationStartTime; + } + + /** + * Set a value indicating the online IR start time. + * + * @param onlineReplicationStartTime the onlineReplicationStartTime value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withOnlineReplicationStartTime(String onlineReplicationStartTime) { + this.onlineReplicationStartTime = onlineReplicationStartTime; + return this; + } + + /** + * Get a value indicating the offline IR import path. + * + * @return the offlineReplicationImportPath value + */ + public String offlineReplicationImportPath() { + return this.offlineReplicationImportPath; + } + + /** + * Set a value indicating the offline IR import path. + * + * @param offlineReplicationImportPath the offlineReplicationImportPath value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withOfflineReplicationImportPath(String offlineReplicationImportPath) { + this.offlineReplicationImportPath = offlineReplicationImportPath; + return this; + } + + /** + * Get a value indicating the offline IR export path. + * + * @return the offlineReplicationExportPath value + */ + public String offlineReplicationExportPath() { + return this.offlineReplicationExportPath; + } + + /** + * Set a value indicating the offline IR export path. + * + * @param offlineReplicationExportPath the offlineReplicationExportPath value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withOfflineReplicationExportPath(String offlineReplicationExportPath) { + this.offlineReplicationExportPath = offlineReplicationExportPath; + return this; + } + + /** + * Get a value indicating the recovery HTTPS port. + * + * @return the replicationPort value + */ + public Integer replicationPort() { + return this.replicationPort; + } + + /** + * Set a value indicating the recovery HTTPS port. + * + * @param replicationPort the replicationPort value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withReplicationPort(Integer replicationPort) { + this.replicationPort = replicationPort; + return this; + } + + /** + * Get a value indicating the authentication type. + * + * @return the allowedAuthenticationType value + */ + public Integer allowedAuthenticationType() { + return this.allowedAuthenticationType; + } + + /** + * Set a value indicating the authentication type. + * + * @param allowedAuthenticationType the allowedAuthenticationType value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withAllowedAuthenticationType(Integer allowedAuthenticationType) { + this.allowedAuthenticationType = allowedAuthenticationType; + return this; + } + + /** + * Get a value indicating whether the VM has to be auto deleted. + * + * @return the replicaDeletion value + */ + public String replicaDeletion() { + return this.replicaDeletion; + } + + /** + * Set a value indicating whether the VM has to be auto deleted. + * + * @param replicaDeletion the replicaDeletion value to set + * @return the HyperVReplicaBluePolicyInput object itself. + */ + public HyperVReplicaBluePolicyInput withReplicaDeletion(String replicaDeletion) { + this.replicaDeletion = replicaDeletion; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBlueReplicationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBlueReplicationDetails.java new file mode 100644 index 0000000000000..5fffe1e8f72f2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaBlueReplicationDetails.java @@ -0,0 +1,205 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * HyperV replica 2012 R2 (Blue) replication details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplica2012R2") +public class HyperVReplicaBlueReplicationDetails extends ReplicationProviderSpecificSettings { + /** + * The Last replication time. + */ + @JsonProperty(value = "lastReplicatedTime") + private DateTime lastReplicatedTime; + + /** + * The PE Network details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * The virtual machine Id. + */ + @JsonProperty(value = "vmId") + private String vmId; + + /** + * The protection state for the vm. + */ + @JsonProperty(value = "vmProtectionState") + private String vmProtectionState; + + /** + * The protection state description for the vm. + */ + @JsonProperty(value = "vmProtectionStateDescription") + private String vmProtectionStateDescription; + + /** + * Initial replication details. + */ + @JsonProperty(value = "initialReplicationDetails") + private InitialReplicationDetails initialReplicationDetails; + + /** + * VM disk details. + */ + @JsonProperty(value = "vMDiskDetails") + private List vMDiskDetails; + + /** + * Get the Last replication time. + * + * @return the lastReplicatedTime value + */ + public DateTime lastReplicatedTime() { + return this.lastReplicatedTime; + } + + /** + * Set the Last replication time. + * + * @param lastReplicatedTime the lastReplicatedTime value to set + * @return the HyperVReplicaBlueReplicationDetails object itself. + */ + public HyperVReplicaBlueReplicationDetails withLastReplicatedTime(DateTime lastReplicatedTime) { + this.lastReplicatedTime = lastReplicatedTime; + return this; + } + + /** + * Get the PE Network details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the PE Network details. + * + * @param vmNics the vmNics value to set + * @return the HyperVReplicaBlueReplicationDetails object itself. + */ + public HyperVReplicaBlueReplicationDetails withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get the virtual machine Id. + * + * @return the vmId value + */ + public String vmId() { + return this.vmId; + } + + /** + * Set the virtual machine Id. + * + * @param vmId the vmId value to set + * @return the HyperVReplicaBlueReplicationDetails object itself. + */ + public HyperVReplicaBlueReplicationDetails withVmId(String vmId) { + this.vmId = vmId; + return this; + } + + /** + * Get the protection state for the vm. + * + * @return the vmProtectionState value + */ + public String vmProtectionState() { + return this.vmProtectionState; + } + + /** + * Set the protection state for the vm. + * + * @param vmProtectionState the vmProtectionState value to set + * @return the HyperVReplicaBlueReplicationDetails object itself. + */ + public HyperVReplicaBlueReplicationDetails withVmProtectionState(String vmProtectionState) { + this.vmProtectionState = vmProtectionState; + return this; + } + + /** + * Get the protection state description for the vm. + * + * @return the vmProtectionStateDescription value + */ + public String vmProtectionStateDescription() { + return this.vmProtectionStateDescription; + } + + /** + * Set the protection state description for the vm. + * + * @param vmProtectionStateDescription the vmProtectionStateDescription value to set + * @return the HyperVReplicaBlueReplicationDetails object itself. + */ + public HyperVReplicaBlueReplicationDetails withVmProtectionStateDescription(String vmProtectionStateDescription) { + this.vmProtectionStateDescription = vmProtectionStateDescription; + return this; + } + + /** + * Get initial replication details. + * + * @return the initialReplicationDetails value + */ + public InitialReplicationDetails initialReplicationDetails() { + return this.initialReplicationDetails; + } + + /** + * Set initial replication details. + * + * @param initialReplicationDetails the initialReplicationDetails value to set + * @return the HyperVReplicaBlueReplicationDetails object itself. + */ + public HyperVReplicaBlueReplicationDetails withInitialReplicationDetails(InitialReplicationDetails initialReplicationDetails) { + this.initialReplicationDetails = initialReplicationDetails; + return this; + } + + /** + * Get vM disk details. + * + * @return the vMDiskDetails value + */ + public List vMDiskDetails() { + return this.vMDiskDetails; + } + + /** + * Set vM disk details. + * + * @param vMDiskDetails the vMDiskDetails value to set + * @return the HyperVReplicaBlueReplicationDetails object itself. + */ + public HyperVReplicaBlueReplicationDetails withVMDiskDetails(List vMDiskDetails) { + this.vMDiskDetails = vMDiskDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaPolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaPolicyDetails.java new file mode 100644 index 0000000000000..d9d1ac89b63d1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaPolicyDetails.java @@ -0,0 +1,282 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Hyper-V Replica Blue specific protection profile details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplica2012") +public class HyperVReplicaPolicyDetails extends PolicyProviderSpecificDetails { + /** + * A value indicating the number of recovery points. + */ + @JsonProperty(value = "recoveryPoints") + private Integer recoveryPoints; + + /** + * A value indicating the application consistent frequency. + */ + @JsonProperty(value = "applicationConsistentSnapshotFrequencyInHours") + private Integer applicationConsistentSnapshotFrequencyInHours; + + /** + * A value indicating whether compression has to be enabled. + */ + @JsonProperty(value = "compression") + private String compression; + + /** + * A value indicating whether IR is online. + */ + @JsonProperty(value = "initialReplicationMethod") + private String initialReplicationMethod; + + /** + * A value indicating the online IR start time. + */ + @JsonProperty(value = "onlineReplicationStartTime") + private String onlineReplicationStartTime; + + /** + * A value indicating the offline IR import path. + */ + @JsonProperty(value = "offlineReplicationImportPath") + private String offlineReplicationImportPath; + + /** + * A value indicating the offline IR export path. + */ + @JsonProperty(value = "offlineReplicationExportPath") + private String offlineReplicationExportPath; + + /** + * A value indicating the recovery HTTPS port. + */ + @JsonProperty(value = "replicationPort") + private Integer replicationPort; + + /** + * A value indicating the authentication type. + */ + @JsonProperty(value = "allowedAuthenticationType") + private Integer allowedAuthenticationType; + + /** + * A value indicating whether the VM has to be auto deleted. Supported + * Values: String.Empty, None, OnRecoveryCloud. + */ + @JsonProperty(value = "replicaDeletionOption") + private String replicaDeletionOption; + + /** + * Get a value indicating the number of recovery points. + * + * @return the recoveryPoints value + */ + public Integer recoveryPoints() { + return this.recoveryPoints; + } + + /** + * Set a value indicating the number of recovery points. + * + * @param recoveryPoints the recoveryPoints value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withRecoveryPoints(Integer recoveryPoints) { + this.recoveryPoints = recoveryPoints; + return this; + } + + /** + * Get a value indicating the application consistent frequency. + * + * @return the applicationConsistentSnapshotFrequencyInHours value + */ + public Integer applicationConsistentSnapshotFrequencyInHours() { + return this.applicationConsistentSnapshotFrequencyInHours; + } + + /** + * Set a value indicating the application consistent frequency. + * + * @param applicationConsistentSnapshotFrequencyInHours the applicationConsistentSnapshotFrequencyInHours value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withApplicationConsistentSnapshotFrequencyInHours(Integer applicationConsistentSnapshotFrequencyInHours) { + this.applicationConsistentSnapshotFrequencyInHours = applicationConsistentSnapshotFrequencyInHours; + return this; + } + + /** + * Get a value indicating whether compression has to be enabled. + * + * @return the compression value + */ + public String compression() { + return this.compression; + } + + /** + * Set a value indicating whether compression has to be enabled. + * + * @param compression the compression value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Get a value indicating whether IR is online. + * + * @return the initialReplicationMethod value + */ + public String initialReplicationMethod() { + return this.initialReplicationMethod; + } + + /** + * Set a value indicating whether IR is online. + * + * @param initialReplicationMethod the initialReplicationMethod value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withInitialReplicationMethod(String initialReplicationMethod) { + this.initialReplicationMethod = initialReplicationMethod; + return this; + } + + /** + * Get a value indicating the online IR start time. + * + * @return the onlineReplicationStartTime value + */ + public String onlineReplicationStartTime() { + return this.onlineReplicationStartTime; + } + + /** + * Set a value indicating the online IR start time. + * + * @param onlineReplicationStartTime the onlineReplicationStartTime value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withOnlineReplicationStartTime(String onlineReplicationStartTime) { + this.onlineReplicationStartTime = onlineReplicationStartTime; + return this; + } + + /** + * Get a value indicating the offline IR import path. + * + * @return the offlineReplicationImportPath value + */ + public String offlineReplicationImportPath() { + return this.offlineReplicationImportPath; + } + + /** + * Set a value indicating the offline IR import path. + * + * @param offlineReplicationImportPath the offlineReplicationImportPath value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withOfflineReplicationImportPath(String offlineReplicationImportPath) { + this.offlineReplicationImportPath = offlineReplicationImportPath; + return this; + } + + /** + * Get a value indicating the offline IR export path. + * + * @return the offlineReplicationExportPath value + */ + public String offlineReplicationExportPath() { + return this.offlineReplicationExportPath; + } + + /** + * Set a value indicating the offline IR export path. + * + * @param offlineReplicationExportPath the offlineReplicationExportPath value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withOfflineReplicationExportPath(String offlineReplicationExportPath) { + this.offlineReplicationExportPath = offlineReplicationExportPath; + return this; + } + + /** + * Get a value indicating the recovery HTTPS port. + * + * @return the replicationPort value + */ + public Integer replicationPort() { + return this.replicationPort; + } + + /** + * Set a value indicating the recovery HTTPS port. + * + * @param replicationPort the replicationPort value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withReplicationPort(Integer replicationPort) { + this.replicationPort = replicationPort; + return this; + } + + /** + * Get a value indicating the authentication type. + * + * @return the allowedAuthenticationType value + */ + public Integer allowedAuthenticationType() { + return this.allowedAuthenticationType; + } + + /** + * Set a value indicating the authentication type. + * + * @param allowedAuthenticationType the allowedAuthenticationType value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withAllowedAuthenticationType(Integer allowedAuthenticationType) { + this.allowedAuthenticationType = allowedAuthenticationType; + return this; + } + + /** + * Get a value indicating whether the VM has to be auto deleted. Supported Values: String.Empty, None, OnRecoveryCloud. + * + * @return the replicaDeletionOption value + */ + public String replicaDeletionOption() { + return this.replicaDeletionOption; + } + + /** + * Set a value indicating whether the VM has to be auto deleted. Supported Values: String.Empty, None, OnRecoveryCloud. + * + * @param replicaDeletionOption the replicaDeletionOption value to set + * @return the HyperVReplicaPolicyDetails object itself. + */ + public HyperVReplicaPolicyDetails withReplicaDeletionOption(String replicaDeletionOption) { + this.replicaDeletionOption = replicaDeletionOption; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaPolicyInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaPolicyInput.java new file mode 100644 index 0000000000000..ac7392e97786c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaPolicyInput.java @@ -0,0 +1,281 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Hyper-V Replica specific policy Input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplica2012") +public class HyperVReplicaPolicyInput extends PolicyProviderSpecificInput { + /** + * A value indicating the number of recovery points. + */ + @JsonProperty(value = "recoveryPoints") + private Integer recoveryPoints; + + /** + * A value indicating the application consistent frequency. + */ + @JsonProperty(value = "applicationConsistentSnapshotFrequencyInHours") + private Integer applicationConsistentSnapshotFrequencyInHours; + + /** + * A value indicating whether compression has to be enabled. + */ + @JsonProperty(value = "compression") + private String compression; + + /** + * A value indicating whether IR is online. + */ + @JsonProperty(value = "initialReplicationMethod") + private String initialReplicationMethod; + + /** + * A value indicating the online IR start time. + */ + @JsonProperty(value = "onlineReplicationStartTime") + private String onlineReplicationStartTime; + + /** + * A value indicating the offline IR import path. + */ + @JsonProperty(value = "offlineReplicationImportPath") + private String offlineReplicationImportPath; + + /** + * A value indicating the offline IR export path. + */ + @JsonProperty(value = "offlineReplicationExportPath") + private String offlineReplicationExportPath; + + /** + * A value indicating the recovery HTTPS port. + */ + @JsonProperty(value = "replicationPort") + private Integer replicationPort; + + /** + * A value indicating the authentication type. + */ + @JsonProperty(value = "allowedAuthenticationType") + private Integer allowedAuthenticationType; + + /** + * A value indicating whether the VM has to be auto deleted. + */ + @JsonProperty(value = "replicaDeletion") + private String replicaDeletion; + + /** + * Get a value indicating the number of recovery points. + * + * @return the recoveryPoints value + */ + public Integer recoveryPoints() { + return this.recoveryPoints; + } + + /** + * Set a value indicating the number of recovery points. + * + * @param recoveryPoints the recoveryPoints value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withRecoveryPoints(Integer recoveryPoints) { + this.recoveryPoints = recoveryPoints; + return this; + } + + /** + * Get a value indicating the application consistent frequency. + * + * @return the applicationConsistentSnapshotFrequencyInHours value + */ + public Integer applicationConsistentSnapshotFrequencyInHours() { + return this.applicationConsistentSnapshotFrequencyInHours; + } + + /** + * Set a value indicating the application consistent frequency. + * + * @param applicationConsistentSnapshotFrequencyInHours the applicationConsistentSnapshotFrequencyInHours value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withApplicationConsistentSnapshotFrequencyInHours(Integer applicationConsistentSnapshotFrequencyInHours) { + this.applicationConsistentSnapshotFrequencyInHours = applicationConsistentSnapshotFrequencyInHours; + return this; + } + + /** + * Get a value indicating whether compression has to be enabled. + * + * @return the compression value + */ + public String compression() { + return this.compression; + } + + /** + * Set a value indicating whether compression has to be enabled. + * + * @param compression the compression value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Get a value indicating whether IR is online. + * + * @return the initialReplicationMethod value + */ + public String initialReplicationMethod() { + return this.initialReplicationMethod; + } + + /** + * Set a value indicating whether IR is online. + * + * @param initialReplicationMethod the initialReplicationMethod value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withInitialReplicationMethod(String initialReplicationMethod) { + this.initialReplicationMethod = initialReplicationMethod; + return this; + } + + /** + * Get a value indicating the online IR start time. + * + * @return the onlineReplicationStartTime value + */ + public String onlineReplicationStartTime() { + return this.onlineReplicationStartTime; + } + + /** + * Set a value indicating the online IR start time. + * + * @param onlineReplicationStartTime the onlineReplicationStartTime value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withOnlineReplicationStartTime(String onlineReplicationStartTime) { + this.onlineReplicationStartTime = onlineReplicationStartTime; + return this; + } + + /** + * Get a value indicating the offline IR import path. + * + * @return the offlineReplicationImportPath value + */ + public String offlineReplicationImportPath() { + return this.offlineReplicationImportPath; + } + + /** + * Set a value indicating the offline IR import path. + * + * @param offlineReplicationImportPath the offlineReplicationImportPath value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withOfflineReplicationImportPath(String offlineReplicationImportPath) { + this.offlineReplicationImportPath = offlineReplicationImportPath; + return this; + } + + /** + * Get a value indicating the offline IR export path. + * + * @return the offlineReplicationExportPath value + */ + public String offlineReplicationExportPath() { + return this.offlineReplicationExportPath; + } + + /** + * Set a value indicating the offline IR export path. + * + * @param offlineReplicationExportPath the offlineReplicationExportPath value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withOfflineReplicationExportPath(String offlineReplicationExportPath) { + this.offlineReplicationExportPath = offlineReplicationExportPath; + return this; + } + + /** + * Get a value indicating the recovery HTTPS port. + * + * @return the replicationPort value + */ + public Integer replicationPort() { + return this.replicationPort; + } + + /** + * Set a value indicating the recovery HTTPS port. + * + * @param replicationPort the replicationPort value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withReplicationPort(Integer replicationPort) { + this.replicationPort = replicationPort; + return this; + } + + /** + * Get a value indicating the authentication type. + * + * @return the allowedAuthenticationType value + */ + public Integer allowedAuthenticationType() { + return this.allowedAuthenticationType; + } + + /** + * Set a value indicating the authentication type. + * + * @param allowedAuthenticationType the allowedAuthenticationType value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withAllowedAuthenticationType(Integer allowedAuthenticationType) { + this.allowedAuthenticationType = allowedAuthenticationType; + return this; + } + + /** + * Get a value indicating whether the VM has to be auto deleted. + * + * @return the replicaDeletion value + */ + public String replicaDeletion() { + return this.replicaDeletion; + } + + /** + * Set a value indicating whether the VM has to be auto deleted. + * + * @param replicaDeletion the replicaDeletion value to set + * @return the HyperVReplicaPolicyInput object itself. + */ + public HyperVReplicaPolicyInput withReplicaDeletion(String replicaDeletion) { + this.replicaDeletion = replicaDeletion; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaReplicationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaReplicationDetails.java new file mode 100644 index 0000000000000..895477982ce20 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVReplicaReplicationDetails.java @@ -0,0 +1,205 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * HyperV replica 2012 replication details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplica2012") +public class HyperVReplicaReplicationDetails extends ReplicationProviderSpecificSettings { + /** + * The Last replication time. + */ + @JsonProperty(value = "lastReplicatedTime") + private DateTime lastReplicatedTime; + + /** + * The PE Network details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * The virtual machine Id. + */ + @JsonProperty(value = "vmId") + private String vmId; + + /** + * The protection state for the vm. + */ + @JsonProperty(value = "vmProtectionState") + private String vmProtectionState; + + /** + * The protection state description for the vm. + */ + @JsonProperty(value = "vmProtectionStateDescription") + private String vmProtectionStateDescription; + + /** + * Initial replication details. + */ + @JsonProperty(value = "initialReplicationDetails") + private InitialReplicationDetails initialReplicationDetails; + + /** + * VM disk details. + */ + @JsonProperty(value = "vMDiskDetails") + private List vMDiskDetails; + + /** + * Get the Last replication time. + * + * @return the lastReplicatedTime value + */ + public DateTime lastReplicatedTime() { + return this.lastReplicatedTime; + } + + /** + * Set the Last replication time. + * + * @param lastReplicatedTime the lastReplicatedTime value to set + * @return the HyperVReplicaReplicationDetails object itself. + */ + public HyperVReplicaReplicationDetails withLastReplicatedTime(DateTime lastReplicatedTime) { + this.lastReplicatedTime = lastReplicatedTime; + return this; + } + + /** + * Get the PE Network details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the PE Network details. + * + * @param vmNics the vmNics value to set + * @return the HyperVReplicaReplicationDetails object itself. + */ + public HyperVReplicaReplicationDetails withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get the virtual machine Id. + * + * @return the vmId value + */ + public String vmId() { + return this.vmId; + } + + /** + * Set the virtual machine Id. + * + * @param vmId the vmId value to set + * @return the HyperVReplicaReplicationDetails object itself. + */ + public HyperVReplicaReplicationDetails withVmId(String vmId) { + this.vmId = vmId; + return this; + } + + /** + * Get the protection state for the vm. + * + * @return the vmProtectionState value + */ + public String vmProtectionState() { + return this.vmProtectionState; + } + + /** + * Set the protection state for the vm. + * + * @param vmProtectionState the vmProtectionState value to set + * @return the HyperVReplicaReplicationDetails object itself. + */ + public HyperVReplicaReplicationDetails withVmProtectionState(String vmProtectionState) { + this.vmProtectionState = vmProtectionState; + return this; + } + + /** + * Get the protection state description for the vm. + * + * @return the vmProtectionStateDescription value + */ + public String vmProtectionStateDescription() { + return this.vmProtectionStateDescription; + } + + /** + * Set the protection state description for the vm. + * + * @param vmProtectionStateDescription the vmProtectionStateDescription value to set + * @return the HyperVReplicaReplicationDetails object itself. + */ + public HyperVReplicaReplicationDetails withVmProtectionStateDescription(String vmProtectionStateDescription) { + this.vmProtectionStateDescription = vmProtectionStateDescription; + return this; + } + + /** + * Get initial replication details. + * + * @return the initialReplicationDetails value + */ + public InitialReplicationDetails initialReplicationDetails() { + return this.initialReplicationDetails; + } + + /** + * Set initial replication details. + * + * @param initialReplicationDetails the initialReplicationDetails value to set + * @return the HyperVReplicaReplicationDetails object itself. + */ + public HyperVReplicaReplicationDetails withInitialReplicationDetails(InitialReplicationDetails initialReplicationDetails) { + this.initialReplicationDetails = initialReplicationDetails; + return this; + } + + /** + * Get vM disk details. + * + * @return the vMDiskDetails value + */ + public List vMDiskDetails() { + return this.vMDiskDetails; + } + + /** + * Set vM disk details. + * + * @param vMDiskDetails the vMDiskDetails value to set + * @return the HyperVReplicaReplicationDetails object itself. + */ + public HyperVReplicaReplicationDetails withVMDiskDetails(List vMDiskDetails) { + this.vMDiskDetails = vMDiskDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVSiteDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVSiteDetails.java new file mode 100644 index 0000000000000..6ddb74e2bea7d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVSiteDetails.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * HyperVSite fabric specific details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVSite") +public class HyperVSiteDetails extends FabricSpecificDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVVirtualMachineDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVVirtualMachineDetails.java new file mode 100644 index 0000000000000..cf850f1799c62 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/HyperVVirtualMachineDetails.java @@ -0,0 +1,210 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Single Host fabric provider specific VM settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVVirtualMachine") +public class HyperVVirtualMachineDetails extends ConfigurationSettings { + /** + * The source id of the object. + */ + @JsonProperty(value = "sourceItemId") + private String sourceItemId; + + /** + * The id of the object in fabric. + */ + @JsonProperty(value = "generation") + private String generation; + + /** + * The Last replication time. + */ + @JsonProperty(value = "osDetails") + private OSDetails osDetails; + + /** + * The Last successful failover time. + */ + @JsonProperty(value = "diskDetails") + private List diskDetails; + + /** + * A value indicating whether the VM has a physical disk attached. String + * value of {SrsDataContract.PresenceStatus} enum. Possible values include: + * 'Unknown', 'Present', 'NotPresent'. + */ + @JsonProperty(value = "hasPhysicalDisk") + private PresenceStatus hasPhysicalDisk; + + /** + * A value indicating whether the VM has a fibre channel adapter attached. + * String value of {SrsDataContract.PresenceStatus} enum. Possible values + * include: 'Unknown', 'Present', 'NotPresent'. + */ + @JsonProperty(value = "hasFibreChannelAdapter") + private PresenceStatus hasFibreChannelAdapter; + + /** + * A value indicating whether the VM has a shared VHD attached. String + * value of {SrsDataContract.PresenceStatus} enum. Possible values include: + * 'Unknown', 'Present', 'NotPresent'. + */ + @JsonProperty(value = "hasSharedVhd") + private PresenceStatus hasSharedVhd; + + /** + * Get the source id of the object. + * + * @return the sourceItemId value + */ + public String sourceItemId() { + return this.sourceItemId; + } + + /** + * Set the source id of the object. + * + * @param sourceItemId the sourceItemId value to set + * @return the HyperVVirtualMachineDetails object itself. + */ + public HyperVVirtualMachineDetails withSourceItemId(String sourceItemId) { + this.sourceItemId = sourceItemId; + return this; + } + + /** + * Get the id of the object in fabric. + * + * @return the generation value + */ + public String generation() { + return this.generation; + } + + /** + * Set the id of the object in fabric. + * + * @param generation the generation value to set + * @return the HyperVVirtualMachineDetails object itself. + */ + public HyperVVirtualMachineDetails withGeneration(String generation) { + this.generation = generation; + return this; + } + + /** + * Get the Last replication time. + * + * @return the osDetails value + */ + public OSDetails osDetails() { + return this.osDetails; + } + + /** + * Set the Last replication time. + * + * @param osDetails the osDetails value to set + * @return the HyperVVirtualMachineDetails object itself. + */ + public HyperVVirtualMachineDetails withOsDetails(OSDetails osDetails) { + this.osDetails = osDetails; + return this; + } + + /** + * Get the Last successful failover time. + * + * @return the diskDetails value + */ + public List diskDetails() { + return this.diskDetails; + } + + /** + * Set the Last successful failover time. + * + * @param diskDetails the diskDetails value to set + * @return the HyperVVirtualMachineDetails object itself. + */ + public HyperVVirtualMachineDetails withDiskDetails(List diskDetails) { + this.diskDetails = diskDetails; + return this; + } + + /** + * Get a value indicating whether the VM has a physical disk attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @return the hasPhysicalDisk value + */ + public PresenceStatus hasPhysicalDisk() { + return this.hasPhysicalDisk; + } + + /** + * Set a value indicating whether the VM has a physical disk attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @param hasPhysicalDisk the hasPhysicalDisk value to set + * @return the HyperVVirtualMachineDetails object itself. + */ + public HyperVVirtualMachineDetails withHasPhysicalDisk(PresenceStatus hasPhysicalDisk) { + this.hasPhysicalDisk = hasPhysicalDisk; + return this; + } + + /** + * Get a value indicating whether the VM has a fibre channel adapter attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @return the hasFibreChannelAdapter value + */ + public PresenceStatus hasFibreChannelAdapter() { + return this.hasFibreChannelAdapter; + } + + /** + * Set a value indicating whether the VM has a fibre channel adapter attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @param hasFibreChannelAdapter the hasFibreChannelAdapter value to set + * @return the HyperVVirtualMachineDetails object itself. + */ + public HyperVVirtualMachineDetails withHasFibreChannelAdapter(PresenceStatus hasFibreChannelAdapter) { + this.hasFibreChannelAdapter = hasFibreChannelAdapter; + return this; + } + + /** + * Get a value indicating whether the VM has a shared VHD attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @return the hasSharedVhd value + */ + public PresenceStatus hasSharedVhd() { + return this.hasSharedVhd; + } + + /** + * Set a value indicating whether the VM has a shared VHD attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @param hasSharedVhd the hasSharedVhd value to set + * @return the HyperVVirtualMachineDetails object itself. + */ + public HyperVVirtualMachineDetails withHasSharedVhd(PresenceStatus hasSharedVhd) { + this.hasSharedVhd = hasSharedVhd; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/IdentityProviderDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/IdentityProviderDetails.java new file mode 100644 index 0000000000000..b93853bb87f3e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/IdentityProviderDetails.java @@ -0,0 +1,155 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Identity provider details. + */ +public class IdentityProviderDetails { + /** + * The tenant Id for the service principal with which the on-premise + * management/data plane components would communicate with our Azure + * services. + */ + @JsonProperty(value = "tenantId") + private String tenantId; + + /** + * The application/client Id for the service principal with which the + * on-premise management/data plane components would communicate with our + * Azure services. + */ + @JsonProperty(value = "applicationId") + private String applicationId; + + /** + * The object Id of the service principal with which the on-premise + * management/data plane components would communicate with our Azure + * services. + */ + @JsonProperty(value = "objectId") + private String objectId; + + /** + * The intended Audience of the service principal with which the on-premise + * management/data plane components would communicate with our Azure + * services. + */ + @JsonProperty(value = "audience") + private String audience; + + /** + * The base authority for Azure Active Directory authentication. + */ + @JsonProperty(value = "aadAuthority") + private String aadAuthority; + + /** + * Get the tenant Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @return the tenantId value + */ + public String tenantId() { + return this.tenantId; + } + + /** + * Set the tenant Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @param tenantId the tenantId value to set + * @return the IdentityProviderDetails object itself. + */ + public IdentityProviderDetails withTenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + /** + * Get the application/client Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @return the applicationId value + */ + public String applicationId() { + return this.applicationId; + } + + /** + * Set the application/client Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @param applicationId the applicationId value to set + * @return the IdentityProviderDetails object itself. + */ + public IdentityProviderDetails withApplicationId(String applicationId) { + this.applicationId = applicationId; + return this; + } + + /** + * Get the object Id of the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @return the objectId value + */ + public String objectId() { + return this.objectId; + } + + /** + * Set the object Id of the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @param objectId the objectId value to set + * @return the IdentityProviderDetails object itself. + */ + public IdentityProviderDetails withObjectId(String objectId) { + this.objectId = objectId; + return this; + } + + /** + * Get the intended Audience of the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @return the audience value + */ + public String audience() { + return this.audience; + } + + /** + * Set the intended Audience of the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @param audience the audience value to set + * @return the IdentityProviderDetails object itself. + */ + public IdentityProviderDetails withAudience(String audience) { + this.audience = audience; + return this; + } + + /** + * Get the base authority for Azure Active Directory authentication. + * + * @return the aadAuthority value + */ + public String aadAuthority() { + return this.aadAuthority; + } + + /** + * Set the base authority for Azure Active Directory authentication. + * + * @param aadAuthority the aadAuthority value to set + * @return the IdentityProviderDetails object itself. + */ + public IdentityProviderDetails withAadAuthority(String aadAuthority) { + this.aadAuthority = aadAuthority; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/IdentityProviderInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/IdentityProviderInput.java new file mode 100644 index 0000000000000..25830bc63fe20 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/IdentityProviderInput.java @@ -0,0 +1,155 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Identity provider input. + */ +public class IdentityProviderInput { + /** + * The tenant Id for the service principal with which the on-premise + * management/data plane components would communicate with our Azure + * services. + */ + @JsonProperty(value = "tenantId", required = true) + private String tenantId; + + /** + * The application/client Id for the service principal with which the + * on-premise management/data plane components would communicate with our + * Azure services. + */ + @JsonProperty(value = "applicationId", required = true) + private String applicationId; + + /** + * The object Id of the service principal with which the on-premise + * management/data plane components would communicate with our Azure + * services. + */ + @JsonProperty(value = "objectId", required = true) + private String objectId; + + /** + * The intended Audience of the service principal with which the on-premise + * management/data plane components would communicate with our Azure + * services. + */ + @JsonProperty(value = "audience", required = true) + private String audience; + + /** + * The base authority for Azure Active Directory authentication. + */ + @JsonProperty(value = "aadAuthority", required = true) + private String aadAuthority; + + /** + * Get the tenant Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @return the tenantId value + */ + public String tenantId() { + return this.tenantId; + } + + /** + * Set the tenant Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @param tenantId the tenantId value to set + * @return the IdentityProviderInput object itself. + */ + public IdentityProviderInput withTenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + /** + * Get the application/client Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @return the applicationId value + */ + public String applicationId() { + return this.applicationId; + } + + /** + * Set the application/client Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @param applicationId the applicationId value to set + * @return the IdentityProviderInput object itself. + */ + public IdentityProviderInput withApplicationId(String applicationId) { + this.applicationId = applicationId; + return this; + } + + /** + * Get the object Id of the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @return the objectId value + */ + public String objectId() { + return this.objectId; + } + + /** + * Set the object Id of the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @param objectId the objectId value to set + * @return the IdentityProviderInput object itself. + */ + public IdentityProviderInput withObjectId(String objectId) { + this.objectId = objectId; + return this; + } + + /** + * Get the intended Audience of the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @return the audience value + */ + public String audience() { + return this.audience; + } + + /** + * Set the intended Audience of the service principal with which the on-premise management/data plane components would communicate with our Azure services. + * + * @param audience the audience value to set + * @return the IdentityProviderInput object itself. + */ + public IdentityProviderInput withAudience(String audience) { + this.audience = audience; + return this; + } + + /** + * Get the base authority for Azure Active Directory authentication. + * + * @return the aadAuthority value + */ + public String aadAuthority() { + return this.aadAuthority; + } + + /** + * Set the base authority for Azure Active Directory authentication. + * + * @param aadAuthority the aadAuthority value to set + * @return the IdentityProviderInput object itself. + */ + public IdentityProviderInput withAadAuthority(String aadAuthority) { + this.aadAuthority = aadAuthority; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAgentDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAgentDetails.java new file mode 100644 index 0000000000000..8955d2714448f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAgentDetails.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The details of the InMage agent. + */ +public class InMageAgentDetails { + /** + * The agent version. + */ + @JsonProperty(value = "agentVersion") + private String agentVersion; + + /** + * A value indicating whether installed agent needs to be updated. + */ + @JsonProperty(value = "agentUpdateStatus") + private String agentUpdateStatus; + + /** + * A value indicating whether reboot is required after update is applied. + */ + @JsonProperty(value = "postUpdateRebootStatus") + private String postUpdateRebootStatus; + + /** + * Agent expiry date. + */ + @JsonProperty(value = "agentExpiryDate") + private DateTime agentExpiryDate; + + /** + * Get the agent version. + * + * @return the agentVersion value + */ + public String agentVersion() { + return this.agentVersion; + } + + /** + * Set the agent version. + * + * @param agentVersion the agentVersion value to set + * @return the InMageAgentDetails object itself. + */ + public InMageAgentDetails withAgentVersion(String agentVersion) { + this.agentVersion = agentVersion; + return this; + } + + /** + * Get a value indicating whether installed agent needs to be updated. + * + * @return the agentUpdateStatus value + */ + public String agentUpdateStatus() { + return this.agentUpdateStatus; + } + + /** + * Set a value indicating whether installed agent needs to be updated. + * + * @param agentUpdateStatus the agentUpdateStatus value to set + * @return the InMageAgentDetails object itself. + */ + public InMageAgentDetails withAgentUpdateStatus(String agentUpdateStatus) { + this.agentUpdateStatus = agentUpdateStatus; + return this; + } + + /** + * Get a value indicating whether reboot is required after update is applied. + * + * @return the postUpdateRebootStatus value + */ + public String postUpdateRebootStatus() { + return this.postUpdateRebootStatus; + } + + /** + * Set a value indicating whether reboot is required after update is applied. + * + * @param postUpdateRebootStatus the postUpdateRebootStatus value to set + * @return the InMageAgentDetails object itself. + */ + public InMageAgentDetails withPostUpdateRebootStatus(String postUpdateRebootStatus) { + this.postUpdateRebootStatus = postUpdateRebootStatus; + return this; + } + + /** + * Get agent expiry date. + * + * @return the agentExpiryDate value + */ + public DateTime agentExpiryDate() { + return this.agentExpiryDate; + } + + /** + * Set agent expiry date. + * + * @param agentExpiryDate the agentExpiryDate value to set + * @return the InMageAgentDetails object itself. + */ + public InMageAgentDetails withAgentExpiryDate(DateTime agentExpiryDate) { + this.agentExpiryDate = agentExpiryDate; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAgentVersionDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAgentVersionDetails.java new file mode 100644 index 0000000000000..3b9646c893395 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAgentVersionDetails.java @@ -0,0 +1,124 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * InMage agent version details. + */ +public class InMageAgentVersionDetails { + /** + * A value indicating whether reboot is required after update is applied. + */ + @JsonProperty(value = "postUpdateRebootStatus") + private String postUpdateRebootStatus; + + /** + * The agent version. + */ + @JsonProperty(value = "version") + private String version; + + /** + * Version expiry date. + */ + @JsonProperty(value = "expiryDate") + private DateTime expiryDate; + + /** + * A value indicating whether security update required. Possible values + * include: 'Supported', 'NotSupported', 'Deprecated', 'UpdateRequired', + * 'SecurityUpdateRequired'. + */ + @JsonProperty(value = "status") + private AgentVersionStatus status; + + /** + * Get a value indicating whether reboot is required after update is applied. + * + * @return the postUpdateRebootStatus value + */ + public String postUpdateRebootStatus() { + return this.postUpdateRebootStatus; + } + + /** + * Set a value indicating whether reboot is required after update is applied. + * + * @param postUpdateRebootStatus the postUpdateRebootStatus value to set + * @return the InMageAgentVersionDetails object itself. + */ + public InMageAgentVersionDetails withPostUpdateRebootStatus(String postUpdateRebootStatus) { + this.postUpdateRebootStatus = postUpdateRebootStatus; + return this; + } + + /** + * Get the agent version. + * + * @return the version value + */ + public String version() { + return this.version; + } + + /** + * Set the agent version. + * + * @param version the version value to set + * @return the InMageAgentVersionDetails object itself. + */ + public InMageAgentVersionDetails withVersion(String version) { + this.version = version; + return this; + } + + /** + * Get version expiry date. + * + * @return the expiryDate value + */ + public DateTime expiryDate() { + return this.expiryDate; + } + + /** + * Set version expiry date. + * + * @param expiryDate the expiryDate value to set + * @return the InMageAgentVersionDetails object itself. + */ + public InMageAgentVersionDetails withExpiryDate(DateTime expiryDate) { + this.expiryDate = expiryDate; + return this; + } + + /** + * Get a value indicating whether security update required. Possible values include: 'Supported', 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'. + * + * @return the status value + */ + public AgentVersionStatus status() { + return this.status; + } + + /** + * Set a value indicating whether security update required. Possible values include: 'Supported', 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'. + * + * @param status the status value to set + * @return the InMageAgentVersionDetails object itself. + */ + public InMageAgentVersionDetails withStatus(AgentVersionStatus status) { + this.status = status; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ApplyRecoveryPointInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ApplyRecoveryPointInput.java new file mode 100644 index 0000000000000..c5b7ef453e448 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ApplyRecoveryPointInput.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * ApplyRecoveryPoint input specific to InMageAzureV2 provider. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2ApplyRecoveryPointInput extends ApplyRecoveryPointProviderSpecificInput { + /** + * The vault location where the recovery Vm resides. + */ + @JsonProperty(value = "vaultLocation") + private String vaultLocation; + + /** + * Get the vault location where the recovery Vm resides. + * + * @return the vaultLocation value + */ + public String vaultLocation() { + return this.vaultLocation; + } + + /** + * Set the vault location where the recovery Vm resides. + * + * @param vaultLocation the vaultLocation value to set + * @return the InMageAzureV2ApplyRecoveryPointInput object itself. + */ + public InMageAzureV2ApplyRecoveryPointInput withVaultLocation(String vaultLocation) { + this.vaultLocation = vaultLocation; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2EnableProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2EnableProtectionInput.java new file mode 100644 index 0000000000000..5eb990297d276 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2EnableProtectionInput.java @@ -0,0 +1,415 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMware Azure specific enable protection input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2EnableProtectionInput extends EnableProtectionProviderSpecificInput { + /** + * The Master target Id. + */ + @JsonProperty(value = "masterTargetId") + private String masterTargetId; + + /** + * The Process Server Id. + */ + @JsonProperty(value = "processServerId") + private String processServerId; + + /** + * The storage account name. + */ + @JsonProperty(value = "storageAccountId", required = true) + private String storageAccountId; + + /** + * The CS account Id. + */ + @JsonProperty(value = "runAsAccountId") + private String runAsAccountId; + + /** + * The multi vm group Id. + */ + @JsonProperty(value = "multiVmGroupId") + private String multiVmGroupId; + + /** + * The multi vm group name. + */ + @JsonProperty(value = "multiVmGroupName") + private String multiVmGroupName; + + /** + * The disks to include list. + */ + @JsonProperty(value = "disksToInclude") + private List disksToInclude; + + /** + * The selected target Azure network Id. + */ + @JsonProperty(value = "targetAzureNetworkId") + private String targetAzureNetworkId; + + /** + * The selected target Azure subnet Id. + */ + @JsonProperty(value = "targetAzureSubnetId") + private String targetAzureSubnetId; + + /** + * The selected option to enable RDP\SSH on target vm after failover. + * String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + */ + @JsonProperty(value = "enableRdpOnTargetOption") + private String enableRdpOnTargetOption; + + /** + * The target azure Vm Name. + */ + @JsonProperty(value = "targetAzureVmName") + private String targetAzureVmName; + + /** + * The storage account to be used for logging during replication. + */ + @JsonProperty(value = "logStorageAccountId") + private String logStorageAccountId; + + /** + * The Id of the target resource group (for classic deployment) in which + * the failover VM is to be created. + */ + @JsonProperty(value = "targetAzureV1ResourceGroupId") + private String targetAzureV1ResourceGroupId; + + /** + * The Id of the target resource group (for resource manager deployment) in + * which the failover VM is to be created. + */ + @JsonProperty(value = "targetAzureV2ResourceGroupId") + private String targetAzureV2ResourceGroupId; + + /** + * A value indicating whether managed disks should be used during failover. + */ + @JsonProperty(value = "useManagedDisks") + private String useManagedDisks; + + /** + * Get the Master target Id. + * + * @return the masterTargetId value + */ + public String masterTargetId() { + return this.masterTargetId; + } + + /** + * Set the Master target Id. + * + * @param masterTargetId the masterTargetId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withMasterTargetId(String masterTargetId) { + this.masterTargetId = masterTargetId; + return this; + } + + /** + * Get the Process Server Id. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the Process Server Id. + * + * @param processServerId the processServerId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the storage account name. + * + * @return the storageAccountId value + */ + public String storageAccountId() { + return this.storageAccountId; + } + + /** + * Set the storage account name. + * + * @param storageAccountId the storageAccountId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withStorageAccountId(String storageAccountId) { + this.storageAccountId = storageAccountId; + return this; + } + + /** + * Get the CS account Id. + * + * @return the runAsAccountId value + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Set the CS account Id. + * + * @param runAsAccountId the runAsAccountId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withRunAsAccountId(String runAsAccountId) { + this.runAsAccountId = runAsAccountId; + return this; + } + + /** + * Get the multi vm group Id. + * + * @return the multiVmGroupId value + */ + public String multiVmGroupId() { + return this.multiVmGroupId; + } + + /** + * Set the multi vm group Id. + * + * @param multiVmGroupId the multiVmGroupId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withMultiVmGroupId(String multiVmGroupId) { + this.multiVmGroupId = multiVmGroupId; + return this; + } + + /** + * Get the multi vm group name. + * + * @return the multiVmGroupName value + */ + public String multiVmGroupName() { + return this.multiVmGroupName; + } + + /** + * Set the multi vm group name. + * + * @param multiVmGroupName the multiVmGroupName value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withMultiVmGroupName(String multiVmGroupName) { + this.multiVmGroupName = multiVmGroupName; + return this; + } + + /** + * Get the disks to include list. + * + * @return the disksToInclude value + */ + public List disksToInclude() { + return this.disksToInclude; + } + + /** + * Set the disks to include list. + * + * @param disksToInclude the disksToInclude value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withDisksToInclude(List disksToInclude) { + this.disksToInclude = disksToInclude; + return this; + } + + /** + * Get the selected target Azure network Id. + * + * @return the targetAzureNetworkId value + */ + public String targetAzureNetworkId() { + return this.targetAzureNetworkId; + } + + /** + * Set the selected target Azure network Id. + * + * @param targetAzureNetworkId the targetAzureNetworkId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withTargetAzureNetworkId(String targetAzureNetworkId) { + this.targetAzureNetworkId = targetAzureNetworkId; + return this; + } + + /** + * Get the selected target Azure subnet Id. + * + * @return the targetAzureSubnetId value + */ + public String targetAzureSubnetId() { + return this.targetAzureSubnetId; + } + + /** + * Set the selected target Azure subnet Id. + * + * @param targetAzureSubnetId the targetAzureSubnetId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withTargetAzureSubnetId(String targetAzureSubnetId) { + this.targetAzureSubnetId = targetAzureSubnetId; + return this; + } + + /** + * Get the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @return the enableRdpOnTargetOption value + */ + public String enableRdpOnTargetOption() { + return this.enableRdpOnTargetOption; + } + + /** + * Set the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @param enableRdpOnTargetOption the enableRdpOnTargetOption value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withEnableRdpOnTargetOption(String enableRdpOnTargetOption) { + this.enableRdpOnTargetOption = enableRdpOnTargetOption; + return this; + } + + /** + * Get the target azure Vm Name. + * + * @return the targetAzureVmName value + */ + public String targetAzureVmName() { + return this.targetAzureVmName; + } + + /** + * Set the target azure Vm Name. + * + * @param targetAzureVmName the targetAzureVmName value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withTargetAzureVmName(String targetAzureVmName) { + this.targetAzureVmName = targetAzureVmName; + return this; + } + + /** + * Get the storage account to be used for logging during replication. + * + * @return the logStorageAccountId value + */ + public String logStorageAccountId() { + return this.logStorageAccountId; + } + + /** + * Set the storage account to be used for logging during replication. + * + * @param logStorageAccountId the logStorageAccountId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withLogStorageAccountId(String logStorageAccountId) { + this.logStorageAccountId = logStorageAccountId; + return this; + } + + /** + * Get the Id of the target resource group (for classic deployment) in which the failover VM is to be created. + * + * @return the targetAzureV1ResourceGroupId value + */ + public String targetAzureV1ResourceGroupId() { + return this.targetAzureV1ResourceGroupId; + } + + /** + * Set the Id of the target resource group (for classic deployment) in which the failover VM is to be created. + * + * @param targetAzureV1ResourceGroupId the targetAzureV1ResourceGroupId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withTargetAzureV1ResourceGroupId(String targetAzureV1ResourceGroupId) { + this.targetAzureV1ResourceGroupId = targetAzureV1ResourceGroupId; + return this; + } + + /** + * Get the Id of the target resource group (for resource manager deployment) in which the failover VM is to be created. + * + * @return the targetAzureV2ResourceGroupId value + */ + public String targetAzureV2ResourceGroupId() { + return this.targetAzureV2ResourceGroupId; + } + + /** + * Set the Id of the target resource group (for resource manager deployment) in which the failover VM is to be created. + * + * @param targetAzureV2ResourceGroupId the targetAzureV2ResourceGroupId value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withTargetAzureV2ResourceGroupId(String targetAzureV2ResourceGroupId) { + this.targetAzureV2ResourceGroupId = targetAzureV2ResourceGroupId; + return this; + } + + /** + * Get a value indicating whether managed disks should be used during failover. + * + * @return the useManagedDisks value + */ + public String useManagedDisks() { + return this.useManagedDisks; + } + + /** + * Set a value indicating whether managed disks should be used during failover. + * + * @param useManagedDisks the useManagedDisks value to set + * @return the InMageAzureV2EnableProtectionInput object itself. + */ + public InMageAzureV2EnableProtectionInput withUseManagedDisks(String useManagedDisks) { + this.useManagedDisks = useManagedDisks; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2EventDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2EventDetails.java new file mode 100644 index 0000000000000..917162ce16406 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2EventDetails.java @@ -0,0 +1,204 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Model class for event details of a VMwareAzureV2 event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2EventDetails extends EventProviderSpecificDetails { + /** + * InMage Event type. Takes one of the values of + * {InMageDataContract.InMageMonitoringEventType}. + */ + @JsonProperty(value = "eventType") + private String eventType; + + /** + * InMage Event Category. + */ + @JsonProperty(value = "category") + private String category; + + /** + * InMage Event Component. + */ + @JsonProperty(value = "component") + private String component; + + /** + * Corrective Action string for the event. + */ + @JsonProperty(value = "correctiveAction") + private String correctiveAction; + + /** + * InMage Event Details. + */ + @JsonProperty(value = "details") + private String details; + + /** + * InMage Event Summary. + */ + @JsonProperty(value = "summary") + private String summary; + + /** + * VMware Site name. + */ + @JsonProperty(value = "siteName") + private String siteName; + + /** + * Get inMage Event type. Takes one of the values of {InMageDataContract.InMageMonitoringEventType}. + * + * @return the eventType value + */ + public String eventType() { + return this.eventType; + } + + /** + * Set inMage Event type. Takes one of the values of {InMageDataContract.InMageMonitoringEventType}. + * + * @param eventType the eventType value to set + * @return the InMageAzureV2EventDetails object itself. + */ + public InMageAzureV2EventDetails withEventType(String eventType) { + this.eventType = eventType; + return this; + } + + /** + * Get inMage Event Category. + * + * @return the category value + */ + public String category() { + return this.category; + } + + /** + * Set inMage Event Category. + * + * @param category the category value to set + * @return the InMageAzureV2EventDetails object itself. + */ + public InMageAzureV2EventDetails withCategory(String category) { + this.category = category; + return this; + } + + /** + * Get inMage Event Component. + * + * @return the component value + */ + public String component() { + return this.component; + } + + /** + * Set inMage Event Component. + * + * @param component the component value to set + * @return the InMageAzureV2EventDetails object itself. + */ + public InMageAzureV2EventDetails withComponent(String component) { + this.component = component; + return this; + } + + /** + * Get corrective Action string for the event. + * + * @return the correctiveAction value + */ + public String correctiveAction() { + return this.correctiveAction; + } + + /** + * Set corrective Action string for the event. + * + * @param correctiveAction the correctiveAction value to set + * @return the InMageAzureV2EventDetails object itself. + */ + public InMageAzureV2EventDetails withCorrectiveAction(String correctiveAction) { + this.correctiveAction = correctiveAction; + return this; + } + + /** + * Get inMage Event Details. + * + * @return the details value + */ + public String details() { + return this.details; + } + + /** + * Set inMage Event Details. + * + * @param details the details value to set + * @return the InMageAzureV2EventDetails object itself. + */ + public InMageAzureV2EventDetails withDetails(String details) { + this.details = details; + return this; + } + + /** + * Get inMage Event Summary. + * + * @return the summary value + */ + public String summary() { + return this.summary; + } + + /** + * Set inMage Event Summary. + * + * @param summary the summary value to set + * @return the InMageAzureV2EventDetails object itself. + */ + public InMageAzureV2EventDetails withSummary(String summary) { + this.summary = summary; + return this; + } + + /** + * Get vMware Site name. + * + * @return the siteName value + */ + public String siteName() { + return this.siteName; + } + + /** + * Set vMware Site name. + * + * @param siteName the siteName value to set + * @return the InMageAzureV2EventDetails object itself. + */ + public InMageAzureV2EventDetails withSiteName(String siteName) { + this.siteName = siteName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2FailoverProviderInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2FailoverProviderInput.java new file mode 100644 index 0000000000000..ba6a8c21faf41 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2FailoverProviderInput.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMageAzureV2 provider specific input for failover. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2FailoverProviderInput extends ProviderSpecificFailoverInput { + /** + * Location of the vault. + */ + @JsonProperty(value = "vaultLocation") + private String vaultLocation; + + /** + * The recovery point id to be passed to failover to a particular recovery + * point. In case of latest recovery point, null should be passed. + */ + @JsonProperty(value = "recoveryPointId") + private String recoveryPointId; + + /** + * Get location of the vault. + * + * @return the vaultLocation value + */ + public String vaultLocation() { + return this.vaultLocation; + } + + /** + * Set location of the vault. + * + * @param vaultLocation the vaultLocation value to set + * @return the InMageAzureV2FailoverProviderInput object itself. + */ + public InMageAzureV2FailoverProviderInput withVaultLocation(String vaultLocation) { + this.vaultLocation = vaultLocation; + return this; + } + + /** + * Get the recovery point id to be passed to failover to a particular recovery point. In case of latest recovery point, null should be passed. + * + * @return the recoveryPointId value + */ + public String recoveryPointId() { + return this.recoveryPointId; + } + + /** + * Set the recovery point id to be passed to failover to a particular recovery point. In case of latest recovery point, null should be passed. + * + * @param recoveryPointId the recoveryPointId value to set + * @return the InMageAzureV2FailoverProviderInput object itself. + */ + public InMageAzureV2FailoverProviderInput withRecoveryPointId(String recoveryPointId) { + this.recoveryPointId = recoveryPointId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2PolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2PolicyDetails.java new file mode 100644 index 0000000000000..dd3f60750d693 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2PolicyDetails.java @@ -0,0 +1,152 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMage Azure v2 specific protection profile details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2PolicyDetails extends PolicyProviderSpecificDetails { + /** + * The crash consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "crashConsistentFrequencyInMinutes") + private Integer crashConsistentFrequencyInMinutes; + + /** + * The recovery point threshold in minutes. + */ + @JsonProperty(value = "recoveryPointThresholdInMinutes") + private Integer recoveryPointThresholdInMinutes; + + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistory") + private Integer recoveryPointHistory; + + /** + * The app consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * A value indicating whether multi-VM sync has to be enabled. + */ + @JsonProperty(value = "multiVmSyncStatus") + private String multiVmSyncStatus; + + /** + * Get the crash consistent snapshot frequency in minutes. + * + * @return the crashConsistentFrequencyInMinutes value + */ + public Integer crashConsistentFrequencyInMinutes() { + return this.crashConsistentFrequencyInMinutes; + } + + /** + * Set the crash consistent snapshot frequency in minutes. + * + * @param crashConsistentFrequencyInMinutes the crashConsistentFrequencyInMinutes value to set + * @return the InMageAzureV2PolicyDetails object itself. + */ + public InMageAzureV2PolicyDetails withCrashConsistentFrequencyInMinutes(Integer crashConsistentFrequencyInMinutes) { + this.crashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes; + return this; + } + + /** + * Get the recovery point threshold in minutes. + * + * @return the recoveryPointThresholdInMinutes value + */ + public Integer recoveryPointThresholdInMinutes() { + return this.recoveryPointThresholdInMinutes; + } + + /** + * Set the recovery point threshold in minutes. + * + * @param recoveryPointThresholdInMinutes the recoveryPointThresholdInMinutes value to set + * @return the InMageAzureV2PolicyDetails object itself. + */ + public InMageAzureV2PolicyDetails withRecoveryPointThresholdInMinutes(Integer recoveryPointThresholdInMinutes) { + this.recoveryPointThresholdInMinutes = recoveryPointThresholdInMinutes; + return this; + } + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistory value + */ + public Integer recoveryPointHistory() { + return this.recoveryPointHistory; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistory the recoveryPointHistory value to set + * @return the InMageAzureV2PolicyDetails object itself. + */ + public InMageAzureV2PolicyDetails withRecoveryPointHistory(Integer recoveryPointHistory) { + this.recoveryPointHistory = recoveryPointHistory; + return this; + } + + /** + * Get the app consistent snapshot frequency in minutes. + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency in minutes. + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the InMageAzureV2PolicyDetails object itself. + */ + public InMageAzureV2PolicyDetails withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get a value indicating whether multi-VM sync has to be enabled. + * + * @return the multiVmSyncStatus value + */ + public String multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi-VM sync has to be enabled. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the InMageAzureV2PolicyDetails object itself. + */ + public InMageAzureV2PolicyDetails withMultiVmSyncStatus(String multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2PolicyInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2PolicyInput.java new file mode 100644 index 0000000000000..d5b35873fe365 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2PolicyInput.java @@ -0,0 +1,154 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMWare Azure specific policy Input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2PolicyInput extends PolicyProviderSpecificInput { + /** + * The recovery point threshold in minutes. + */ + @JsonProperty(value = "recoveryPointThresholdInMinutes") + private Integer recoveryPointThresholdInMinutes; + + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistory") + private Integer recoveryPointHistory; + + /** + * The crash consistent snapshot frequency (in minutes). + */ + @JsonProperty(value = "crashConsistentFrequencyInMinutes") + private Integer crashConsistentFrequencyInMinutes; + + /** + * The app consistent snapshot frequency (in minutes). + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * A value indicating whether multi-VM sync has to be enabled. Value should + * be 'Enabled' or 'Disabled'. Possible values include: 'Enable', + * 'Disable'. + */ + @JsonProperty(value = "multiVmSyncStatus", required = true) + private SetMultiVmSyncStatus multiVmSyncStatus; + + /** + * Get the recovery point threshold in minutes. + * + * @return the recoveryPointThresholdInMinutes value + */ + public Integer recoveryPointThresholdInMinutes() { + return this.recoveryPointThresholdInMinutes; + } + + /** + * Set the recovery point threshold in minutes. + * + * @param recoveryPointThresholdInMinutes the recoveryPointThresholdInMinutes value to set + * @return the InMageAzureV2PolicyInput object itself. + */ + public InMageAzureV2PolicyInput withRecoveryPointThresholdInMinutes(Integer recoveryPointThresholdInMinutes) { + this.recoveryPointThresholdInMinutes = recoveryPointThresholdInMinutes; + return this; + } + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistory value + */ + public Integer recoveryPointHistory() { + return this.recoveryPointHistory; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistory the recoveryPointHistory value to set + * @return the InMageAzureV2PolicyInput object itself. + */ + public InMageAzureV2PolicyInput withRecoveryPointHistory(Integer recoveryPointHistory) { + this.recoveryPointHistory = recoveryPointHistory; + return this; + } + + /** + * Get the crash consistent snapshot frequency (in minutes). + * + * @return the crashConsistentFrequencyInMinutes value + */ + public Integer crashConsistentFrequencyInMinutes() { + return this.crashConsistentFrequencyInMinutes; + } + + /** + * Set the crash consistent snapshot frequency (in minutes). + * + * @param crashConsistentFrequencyInMinutes the crashConsistentFrequencyInMinutes value to set + * @return the InMageAzureV2PolicyInput object itself. + */ + public InMageAzureV2PolicyInput withCrashConsistentFrequencyInMinutes(Integer crashConsistentFrequencyInMinutes) { + this.crashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes; + return this; + } + + /** + * Get the app consistent snapshot frequency (in minutes). + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency (in minutes). + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the InMageAzureV2PolicyInput object itself. + */ + public InMageAzureV2PolicyInput withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get a value indicating whether multi-VM sync has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values include: 'Enable', 'Disable'. + * + * @return the multiVmSyncStatus value + */ + public SetMultiVmSyncStatus multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi-VM sync has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values include: 'Enable', 'Disable'. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the InMageAzureV2PolicyInput object itself. + */ + public InMageAzureV2PolicyInput withMultiVmSyncStatus(SetMultiVmSyncStatus multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ProtectedDiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ProtectedDiskDetails.java new file mode 100644 index 0000000000000..a82740b62ac33 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ProtectedDiskDetails.java @@ -0,0 +1,408 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * InMageAzureV2 protected disk details. + */ +public class InMageAzureV2ProtectedDiskDetails { + /** + * The disk id. + */ + @JsonProperty(value = "diskId") + private String diskId; + + /** + * The disk name. + */ + @JsonProperty(value = "diskName") + private String diskName; + + /** + * The protection stage. + */ + @JsonProperty(value = "protectionStage") + private String protectionStage; + + /** + * The health error code for the disk. + */ + @JsonProperty(value = "healthErrorCode") + private String healthErrorCode; + + /** + * The RPO in seconds. + */ + @JsonProperty(value = "rpoInSeconds") + private Long rpoInSeconds; + + /** + * A value indicating whether resync is required for this disk. + */ + @JsonProperty(value = "resyncRequired") + private String resyncRequired; + + /** + * The resync progress percentage. + */ + @JsonProperty(value = "resyncProgressPercentage") + private Integer resyncProgressPercentage; + + /** + * The resync duration in seconds. + */ + @JsonProperty(value = "resyncDurationInSeconds") + private Long resyncDurationInSeconds; + + /** + * The disk capacity in bytes. + */ + @JsonProperty(value = "diskCapacityInBytes") + private Long diskCapacityInBytes; + + /** + * The disk file system capacity in bytes. + */ + @JsonProperty(value = "fileSystemCapacityInBytes") + private Long fileSystemCapacityInBytes; + + /** + * The source data transit in MB. + */ + @JsonProperty(value = "sourceDataInMegaBytes") + private Double sourceDataInMegaBytes; + + /** + * The PS data transit in MB. + */ + @JsonProperty(value = "psDataInMegaBytes") + private Double psDataInMegaBytes; + + /** + * The target data transit in MB. + */ + @JsonProperty(value = "targetDataInMegaBytes") + private Double targetDataInMegaBytes; + + /** + * A value indicating whether disk is resized. + */ + @JsonProperty(value = "diskResized") + private String diskResized; + + /** + * The last RPO calculated time. + */ + @JsonProperty(value = "lastRpoCalculatedTime") + private DateTime lastRpoCalculatedTime; + + /** + * Get the disk id. + * + * @return the diskId value + */ + public String diskId() { + return this.diskId; + } + + /** + * Set the disk id. + * + * @param diskId the diskId value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withDiskId(String diskId) { + this.diskId = diskId; + return this; + } + + /** + * Get the disk name. + * + * @return the diskName value + */ + public String diskName() { + return this.diskName; + } + + /** + * Set the disk name. + * + * @param diskName the diskName value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withDiskName(String diskName) { + this.diskName = diskName; + return this; + } + + /** + * Get the protection stage. + * + * @return the protectionStage value + */ + public String protectionStage() { + return this.protectionStage; + } + + /** + * Set the protection stage. + * + * @param protectionStage the protectionStage value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withProtectionStage(String protectionStage) { + this.protectionStage = protectionStage; + return this; + } + + /** + * Get the health error code for the disk. + * + * @return the healthErrorCode value + */ + public String healthErrorCode() { + return this.healthErrorCode; + } + + /** + * Set the health error code for the disk. + * + * @param healthErrorCode the healthErrorCode value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withHealthErrorCode(String healthErrorCode) { + this.healthErrorCode = healthErrorCode; + return this; + } + + /** + * Get the RPO in seconds. + * + * @return the rpoInSeconds value + */ + public Long rpoInSeconds() { + return this.rpoInSeconds; + } + + /** + * Set the RPO in seconds. + * + * @param rpoInSeconds the rpoInSeconds value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withRpoInSeconds(Long rpoInSeconds) { + this.rpoInSeconds = rpoInSeconds; + return this; + } + + /** + * Get a value indicating whether resync is required for this disk. + * + * @return the resyncRequired value + */ + public String resyncRequired() { + return this.resyncRequired; + } + + /** + * Set a value indicating whether resync is required for this disk. + * + * @param resyncRequired the resyncRequired value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withResyncRequired(String resyncRequired) { + this.resyncRequired = resyncRequired; + return this; + } + + /** + * Get the resync progress percentage. + * + * @return the resyncProgressPercentage value + */ + public Integer resyncProgressPercentage() { + return this.resyncProgressPercentage; + } + + /** + * Set the resync progress percentage. + * + * @param resyncProgressPercentage the resyncProgressPercentage value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withResyncProgressPercentage(Integer resyncProgressPercentage) { + this.resyncProgressPercentage = resyncProgressPercentage; + return this; + } + + /** + * Get the resync duration in seconds. + * + * @return the resyncDurationInSeconds value + */ + public Long resyncDurationInSeconds() { + return this.resyncDurationInSeconds; + } + + /** + * Set the resync duration in seconds. + * + * @param resyncDurationInSeconds the resyncDurationInSeconds value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withResyncDurationInSeconds(Long resyncDurationInSeconds) { + this.resyncDurationInSeconds = resyncDurationInSeconds; + return this; + } + + /** + * Get the disk capacity in bytes. + * + * @return the diskCapacityInBytes value + */ + public Long diskCapacityInBytes() { + return this.diskCapacityInBytes; + } + + /** + * Set the disk capacity in bytes. + * + * @param diskCapacityInBytes the diskCapacityInBytes value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withDiskCapacityInBytes(Long diskCapacityInBytes) { + this.diskCapacityInBytes = diskCapacityInBytes; + return this; + } + + /** + * Get the disk file system capacity in bytes. + * + * @return the fileSystemCapacityInBytes value + */ + public Long fileSystemCapacityInBytes() { + return this.fileSystemCapacityInBytes; + } + + /** + * Set the disk file system capacity in bytes. + * + * @param fileSystemCapacityInBytes the fileSystemCapacityInBytes value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withFileSystemCapacityInBytes(Long fileSystemCapacityInBytes) { + this.fileSystemCapacityInBytes = fileSystemCapacityInBytes; + return this; + } + + /** + * Get the source data transit in MB. + * + * @return the sourceDataInMegaBytes value + */ + public Double sourceDataInMegaBytes() { + return this.sourceDataInMegaBytes; + } + + /** + * Set the source data transit in MB. + * + * @param sourceDataInMegaBytes the sourceDataInMegaBytes value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withSourceDataInMegaBytes(Double sourceDataInMegaBytes) { + this.sourceDataInMegaBytes = sourceDataInMegaBytes; + return this; + } + + /** + * Get the PS data transit in MB. + * + * @return the psDataInMegaBytes value + */ + public Double psDataInMegaBytes() { + return this.psDataInMegaBytes; + } + + /** + * Set the PS data transit in MB. + * + * @param psDataInMegaBytes the psDataInMegaBytes value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withPsDataInMegaBytes(Double psDataInMegaBytes) { + this.psDataInMegaBytes = psDataInMegaBytes; + return this; + } + + /** + * Get the target data transit in MB. + * + * @return the targetDataInMegaBytes value + */ + public Double targetDataInMegaBytes() { + return this.targetDataInMegaBytes; + } + + /** + * Set the target data transit in MB. + * + * @param targetDataInMegaBytes the targetDataInMegaBytes value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withTargetDataInMegaBytes(Double targetDataInMegaBytes) { + this.targetDataInMegaBytes = targetDataInMegaBytes; + return this; + } + + /** + * Get a value indicating whether disk is resized. + * + * @return the diskResized value + */ + public String diskResized() { + return this.diskResized; + } + + /** + * Set a value indicating whether disk is resized. + * + * @param diskResized the diskResized value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withDiskResized(String diskResized) { + this.diskResized = diskResized; + return this; + } + + /** + * Get the last RPO calculated time. + * + * @return the lastRpoCalculatedTime value + */ + public DateTime lastRpoCalculatedTime() { + return this.lastRpoCalculatedTime; + } + + /** + * Set the last RPO calculated time. + * + * @param lastRpoCalculatedTime the lastRpoCalculatedTime value to set + * @return the InMageAzureV2ProtectedDiskDetails object itself. + */ + public InMageAzureV2ProtectedDiskDetails withLastRpoCalculatedTime(DateTime lastRpoCalculatedTime) { + this.lastRpoCalculatedTime = lastRpoCalculatedTime; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2RecoveryPointDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2RecoveryPointDetails.java new file mode 100644 index 0000000000000..dce8c9a3bb3dc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2RecoveryPointDetails.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMage Azure V2 provider specific recovery point details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2RecoveryPointDetails extends ProviderSpecificRecoveryPointDetails { + /** + * A value indicating whether the recovery point is multi VM consistent. + */ + @JsonProperty(value = "isMultiVmSyncPoint") + private String isMultiVmSyncPoint; + + /** + * Get a value indicating whether the recovery point is multi VM consistent. + * + * @return the isMultiVmSyncPoint value + */ + public String isMultiVmSyncPoint() { + return this.isMultiVmSyncPoint; + } + + /** + * Set a value indicating whether the recovery point is multi VM consistent. + * + * @param isMultiVmSyncPoint the isMultiVmSyncPoint value to set + * @return the InMageAzureV2RecoveryPointDetails object itself. + */ + public InMageAzureV2RecoveryPointDetails withIsMultiVmSyncPoint(String isMultiVmSyncPoint) { + this.isMultiVmSyncPoint = isMultiVmSyncPoint; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ReplicationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ReplicationDetails.java new file mode 100644 index 0000000000000..f9ba467dd9428 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ReplicationDetails.java @@ -0,0 +1,1307 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMageAzureV2 provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2ReplicationDetails extends ReplicationProviderSpecificSettings { + /** + * The infrastructure VM Id. + */ + @JsonProperty(value = "infrastructureVmId") + private String infrastructureVmId; + + /** + * The vCenter infrastructure Id. + */ + @JsonProperty(value = "vCenterInfrastructureId") + private String vCenterInfrastructureId; + + /** + * The protection stage. + */ + @JsonProperty(value = "protectionStage") + private String protectionStage; + + /** + * The virtual machine Id. + */ + @JsonProperty(value = "vmId") + private String vmId; + + /** + * The protection state for the vm. + */ + @JsonProperty(value = "vmProtectionState") + private String vmProtectionState; + + /** + * The protection state description for the vm. + */ + @JsonProperty(value = "vmProtectionStateDescription") + private String vmProtectionStateDescription; + + /** + * The resync progress percentage. + */ + @JsonProperty(value = "resyncProgressPercentage") + private Integer resyncProgressPercentage; + + /** + * The RPO in seconds. + */ + @JsonProperty(value = "rpoInSeconds") + private Long rpoInSeconds; + + /** + * The compressed data change rate in MB. + */ + @JsonProperty(value = "compressedDataRateInMB") + private Double compressedDataRateInMB; + + /** + * The uncompressed data change rate in MB. + */ + @JsonProperty(value = "uncompressedDataRateInMB") + private Double uncompressedDataRateInMB; + + /** + * The source IP address. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The agent version. + */ + @JsonProperty(value = "agentVersion") + private String agentVersion; + + /** + * Agent expiry date. + */ + @JsonProperty(value = "agentExpiryDate") + private DateTime agentExpiryDate; + + /** + * A value indicating whether installed agent needs to be updated. + */ + @JsonProperty(value = "isAgentUpdateRequired") + private String isAgentUpdateRequired; + + /** + * A value indicating whether the source server requires a restart after + * update. + */ + @JsonProperty(value = "isRebootAfterUpdateRequired") + private String isRebootAfterUpdateRequired; + + /** + * The last heartbeat received from the source server. + */ + @JsonProperty(value = "lastHeartbeat") + private DateTime lastHeartbeat; + + /** + * The process server Id. + */ + @JsonProperty(value = "processServerId") + private String processServerId; + + /** + * The multi vm group Id. + */ + @JsonProperty(value = "multiVmGroupId") + private String multiVmGroupId; + + /** + * The multi vm group name. + */ + @JsonProperty(value = "multiVmGroupName") + private String multiVmGroupName; + + /** + * A value indicating whether multi vm sync is enabled or disabled. + */ + @JsonProperty(value = "multiVmSyncStatus") + private String multiVmSyncStatus; + + /** + * The list of protected disks. + */ + @JsonProperty(value = "protectedDisks") + private List protectedDisks; + + /** + * A value indicating whether any disk is resized for this VM. + */ + @JsonProperty(value = "diskResized") + private String diskResized; + + /** + * The master target Id. + */ + @JsonProperty(value = "masterTargetId") + private String masterTargetId; + + /** + * The CPU count of the VM on the primary side. + */ + @JsonProperty(value = "sourceVmCpuCount") + private Integer sourceVmCpuCount; + + /** + * The RAM size of the VM on the primary side. + */ + @JsonProperty(value = "sourceVmRamSizeInMB") + private Integer sourceVmRamSizeInMB; + + /** + * The type of the OS on the VM. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * The OS disk VHD name. + */ + @JsonProperty(value = "vhdName") + private String vhdName; + + /** + * The id of the disk containing the OS. + */ + @JsonProperty(value = "osDiskId") + private String osDiskId; + + /** + * Azure VM Disk details. + */ + @JsonProperty(value = "azureVMDiskDetails") + private List azureVMDiskDetails; + + /** + * Recovery Azure given name. + */ + @JsonProperty(value = "recoveryAzureVMName") + private String recoveryAzureVMName; + + /** + * The Recovery Azure VM size. + */ + @JsonProperty(value = "recoveryAzureVMSize") + private String recoveryAzureVMSize; + + /** + * The recovery Azure storage account. + */ + @JsonProperty(value = "recoveryAzureStorageAccount") + private String recoveryAzureStorageAccount; + + /** + * The ARM id of the log storage account used for replication. This will be + * set to null if no log storage account was provided during enable + * protection. + */ + @JsonProperty(value = "recoveryAzureLogStorageAccountId") + private String recoveryAzureLogStorageAccountId; + + /** + * The PE Network details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * The selected recovery azure network Id. + */ + @JsonProperty(value = "selectedRecoveryAzureNetworkId") + private String selectedRecoveryAzureNetworkId; + + /** + * The selected source nic Id which will be used as the primary nic during + * failover. + */ + @JsonProperty(value = "selectedSourceNicId") + private String selectedSourceNicId; + + /** + * A value indicating the discovery type of the machine. Value can be + * vCenter or physical. + */ + @JsonProperty(value = "discoveryType") + private String discoveryType; + + /** + * The selected option to enable RDP\SSH on target vm after failover. + * String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + */ + @JsonProperty(value = "enableRdpOnTargetOption") + private String enableRdpOnTargetOption; + + /** + * The data stores of the on-premise machine. Value can be list of strings + * that contain data store names. + */ + @JsonProperty(value = "datastores") + private List datastores; + + /** + * The ARM Id of the target Azure VM. This value will be null until the VM + * is failed over. Only after failure it will be populated with the ARM Id + * of the Azure VM. + */ + @JsonProperty(value = "targetVmId") + private String targetVmId; + + /** + * The target resource group Id. + */ + @JsonProperty(value = "recoveryAzureResourceGroupId") + private String recoveryAzureResourceGroupId; + + /** + * The recovery availability set Id. + */ + @JsonProperty(value = "recoveryAvailabilitySetId") + private String recoveryAvailabilitySetId; + + /** + * A value indicating whether managed disks should be used during failover. + */ + @JsonProperty(value = "useManagedDisks") + private String useManagedDisks; + + /** + * License Type of the VM to be used. + */ + @JsonProperty(value = "licenseType") + private String licenseType; + + /** + * The validation errors of the on-premise machine Value can be list of + * validation errors. + */ + @JsonProperty(value = "validationErrors") + private List validationErrors; + + /** + * The last RPO calculated time. + */ + @JsonProperty(value = "lastRpoCalculatedTime") + private DateTime lastRpoCalculatedTime; + + /** + * The last update time received from on-prem components. + */ + @JsonProperty(value = "lastUpdateReceivedTime") + private DateTime lastUpdateReceivedTime; + + /** + * The replica id of the protected item. + */ + @JsonProperty(value = "replicaId") + private String replicaId; + + /** + * The OS Version of the protected item. + */ + @JsonProperty(value = "osVersion") + private String osVersion; + + /** + * Get the infrastructure VM Id. + * + * @return the infrastructureVmId value + */ + public String infrastructureVmId() { + return this.infrastructureVmId; + } + + /** + * Set the infrastructure VM Id. + * + * @param infrastructureVmId the infrastructureVmId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withInfrastructureVmId(String infrastructureVmId) { + this.infrastructureVmId = infrastructureVmId; + return this; + } + + /** + * Get the vCenter infrastructure Id. + * + * @return the vCenterInfrastructureId value + */ + public String vCenterInfrastructureId() { + return this.vCenterInfrastructureId; + } + + /** + * Set the vCenter infrastructure Id. + * + * @param vCenterInfrastructureId the vCenterInfrastructureId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withVCenterInfrastructureId(String vCenterInfrastructureId) { + this.vCenterInfrastructureId = vCenterInfrastructureId; + return this; + } + + /** + * Get the protection stage. + * + * @return the protectionStage value + */ + public String protectionStage() { + return this.protectionStage; + } + + /** + * Set the protection stage. + * + * @param protectionStage the protectionStage value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withProtectionStage(String protectionStage) { + this.protectionStage = protectionStage; + return this; + } + + /** + * Get the virtual machine Id. + * + * @return the vmId value + */ + public String vmId() { + return this.vmId; + } + + /** + * Set the virtual machine Id. + * + * @param vmId the vmId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withVmId(String vmId) { + this.vmId = vmId; + return this; + } + + /** + * Get the protection state for the vm. + * + * @return the vmProtectionState value + */ + public String vmProtectionState() { + return this.vmProtectionState; + } + + /** + * Set the protection state for the vm. + * + * @param vmProtectionState the vmProtectionState value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withVmProtectionState(String vmProtectionState) { + this.vmProtectionState = vmProtectionState; + return this; + } + + /** + * Get the protection state description for the vm. + * + * @return the vmProtectionStateDescription value + */ + public String vmProtectionStateDescription() { + return this.vmProtectionStateDescription; + } + + /** + * Set the protection state description for the vm. + * + * @param vmProtectionStateDescription the vmProtectionStateDescription value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withVmProtectionStateDescription(String vmProtectionStateDescription) { + this.vmProtectionStateDescription = vmProtectionStateDescription; + return this; + } + + /** + * Get the resync progress percentage. + * + * @return the resyncProgressPercentage value + */ + public Integer resyncProgressPercentage() { + return this.resyncProgressPercentage; + } + + /** + * Set the resync progress percentage. + * + * @param resyncProgressPercentage the resyncProgressPercentage value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withResyncProgressPercentage(Integer resyncProgressPercentage) { + this.resyncProgressPercentage = resyncProgressPercentage; + return this; + } + + /** + * Get the RPO in seconds. + * + * @return the rpoInSeconds value + */ + public Long rpoInSeconds() { + return this.rpoInSeconds; + } + + /** + * Set the RPO in seconds. + * + * @param rpoInSeconds the rpoInSeconds value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withRpoInSeconds(Long rpoInSeconds) { + this.rpoInSeconds = rpoInSeconds; + return this; + } + + /** + * Get the compressed data change rate in MB. + * + * @return the compressedDataRateInMB value + */ + public Double compressedDataRateInMB() { + return this.compressedDataRateInMB; + } + + /** + * Set the compressed data change rate in MB. + * + * @param compressedDataRateInMB the compressedDataRateInMB value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withCompressedDataRateInMB(Double compressedDataRateInMB) { + this.compressedDataRateInMB = compressedDataRateInMB; + return this; + } + + /** + * Get the uncompressed data change rate in MB. + * + * @return the uncompressedDataRateInMB value + */ + public Double uncompressedDataRateInMB() { + return this.uncompressedDataRateInMB; + } + + /** + * Set the uncompressed data change rate in MB. + * + * @param uncompressedDataRateInMB the uncompressedDataRateInMB value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withUncompressedDataRateInMB(Double uncompressedDataRateInMB) { + this.uncompressedDataRateInMB = uncompressedDataRateInMB; + return this; + } + + /** + * Get the source IP address. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the source IP address. + * + * @param ipAddress the ipAddress value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the agent version. + * + * @return the agentVersion value + */ + public String agentVersion() { + return this.agentVersion; + } + + /** + * Set the agent version. + * + * @param agentVersion the agentVersion value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withAgentVersion(String agentVersion) { + this.agentVersion = agentVersion; + return this; + } + + /** + * Get agent expiry date. + * + * @return the agentExpiryDate value + */ + public DateTime agentExpiryDate() { + return this.agentExpiryDate; + } + + /** + * Set agent expiry date. + * + * @param agentExpiryDate the agentExpiryDate value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withAgentExpiryDate(DateTime agentExpiryDate) { + this.agentExpiryDate = agentExpiryDate; + return this; + } + + /** + * Get a value indicating whether installed agent needs to be updated. + * + * @return the isAgentUpdateRequired value + */ + public String isAgentUpdateRequired() { + return this.isAgentUpdateRequired; + } + + /** + * Set a value indicating whether installed agent needs to be updated. + * + * @param isAgentUpdateRequired the isAgentUpdateRequired value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withIsAgentUpdateRequired(String isAgentUpdateRequired) { + this.isAgentUpdateRequired = isAgentUpdateRequired; + return this; + } + + /** + * Get a value indicating whether the source server requires a restart after update. + * + * @return the isRebootAfterUpdateRequired value + */ + public String isRebootAfterUpdateRequired() { + return this.isRebootAfterUpdateRequired; + } + + /** + * Set a value indicating whether the source server requires a restart after update. + * + * @param isRebootAfterUpdateRequired the isRebootAfterUpdateRequired value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withIsRebootAfterUpdateRequired(String isRebootAfterUpdateRequired) { + this.isRebootAfterUpdateRequired = isRebootAfterUpdateRequired; + return this; + } + + /** + * Get the last heartbeat received from the source server. + * + * @return the lastHeartbeat value + */ + public DateTime lastHeartbeat() { + return this.lastHeartbeat; + } + + /** + * Set the last heartbeat received from the source server. + * + * @param lastHeartbeat the lastHeartbeat value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withLastHeartbeat(DateTime lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + return this; + } + + /** + * Get the process server Id. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the process server Id. + * + * @param processServerId the processServerId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the multi vm group Id. + * + * @return the multiVmGroupId value + */ + public String multiVmGroupId() { + return this.multiVmGroupId; + } + + /** + * Set the multi vm group Id. + * + * @param multiVmGroupId the multiVmGroupId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withMultiVmGroupId(String multiVmGroupId) { + this.multiVmGroupId = multiVmGroupId; + return this; + } + + /** + * Get the multi vm group name. + * + * @return the multiVmGroupName value + */ + public String multiVmGroupName() { + return this.multiVmGroupName; + } + + /** + * Set the multi vm group name. + * + * @param multiVmGroupName the multiVmGroupName value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withMultiVmGroupName(String multiVmGroupName) { + this.multiVmGroupName = multiVmGroupName; + return this; + } + + /** + * Get a value indicating whether multi vm sync is enabled or disabled. + * + * @return the multiVmSyncStatus value + */ + public String multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi vm sync is enabled or disabled. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withMultiVmSyncStatus(String multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + + /** + * Get the list of protected disks. + * + * @return the protectedDisks value + */ + public List protectedDisks() { + return this.protectedDisks; + } + + /** + * Set the list of protected disks. + * + * @param protectedDisks the protectedDisks value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withProtectedDisks(List protectedDisks) { + this.protectedDisks = protectedDisks; + return this; + } + + /** + * Get a value indicating whether any disk is resized for this VM. + * + * @return the diskResized value + */ + public String diskResized() { + return this.diskResized; + } + + /** + * Set a value indicating whether any disk is resized for this VM. + * + * @param diskResized the diskResized value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withDiskResized(String diskResized) { + this.diskResized = diskResized; + return this; + } + + /** + * Get the master target Id. + * + * @return the masterTargetId value + */ + public String masterTargetId() { + return this.masterTargetId; + } + + /** + * Set the master target Id. + * + * @param masterTargetId the masterTargetId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withMasterTargetId(String masterTargetId) { + this.masterTargetId = masterTargetId; + return this; + } + + /** + * Get the CPU count of the VM on the primary side. + * + * @return the sourceVmCpuCount value + */ + public Integer sourceVmCpuCount() { + return this.sourceVmCpuCount; + } + + /** + * Set the CPU count of the VM on the primary side. + * + * @param sourceVmCpuCount the sourceVmCpuCount value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withSourceVmCpuCount(Integer sourceVmCpuCount) { + this.sourceVmCpuCount = sourceVmCpuCount; + return this; + } + + /** + * Get the RAM size of the VM on the primary side. + * + * @return the sourceVmRamSizeInMB value + */ + public Integer sourceVmRamSizeInMB() { + return this.sourceVmRamSizeInMB; + } + + /** + * Set the RAM size of the VM on the primary side. + * + * @param sourceVmRamSizeInMB the sourceVmRamSizeInMB value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withSourceVmRamSizeInMB(Integer sourceVmRamSizeInMB) { + this.sourceVmRamSizeInMB = sourceVmRamSizeInMB; + return this; + } + + /** + * Get the type of the OS on the VM. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the type of the OS on the VM. + * + * @param osType the osType value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get the OS disk VHD name. + * + * @return the vhdName value + */ + public String vhdName() { + return this.vhdName; + } + + /** + * Set the OS disk VHD name. + * + * @param vhdName the vhdName value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withVhdName(String vhdName) { + this.vhdName = vhdName; + return this; + } + + /** + * Get the id of the disk containing the OS. + * + * @return the osDiskId value + */ + public String osDiskId() { + return this.osDiskId; + } + + /** + * Set the id of the disk containing the OS. + * + * @param osDiskId the osDiskId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withOsDiskId(String osDiskId) { + this.osDiskId = osDiskId; + return this; + } + + /** + * Get azure VM Disk details. + * + * @return the azureVMDiskDetails value + */ + public List azureVMDiskDetails() { + return this.azureVMDiskDetails; + } + + /** + * Set azure VM Disk details. + * + * @param azureVMDiskDetails the azureVMDiskDetails value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withAzureVMDiskDetails(List azureVMDiskDetails) { + this.azureVMDiskDetails = azureVMDiskDetails; + return this; + } + + /** + * Get recovery Azure given name. + * + * @return the recoveryAzureVMName value + */ + public String recoveryAzureVMName() { + return this.recoveryAzureVMName; + } + + /** + * Set recovery Azure given name. + * + * @param recoveryAzureVMName the recoveryAzureVMName value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withRecoveryAzureVMName(String recoveryAzureVMName) { + this.recoveryAzureVMName = recoveryAzureVMName; + return this; + } + + /** + * Get the Recovery Azure VM size. + * + * @return the recoveryAzureVMSize value + */ + public String recoveryAzureVMSize() { + return this.recoveryAzureVMSize; + } + + /** + * Set the Recovery Azure VM size. + * + * @param recoveryAzureVMSize the recoveryAzureVMSize value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withRecoveryAzureVMSize(String recoveryAzureVMSize) { + this.recoveryAzureVMSize = recoveryAzureVMSize; + return this; + } + + /** + * Get the recovery Azure storage account. + * + * @return the recoveryAzureStorageAccount value + */ + public String recoveryAzureStorageAccount() { + return this.recoveryAzureStorageAccount; + } + + /** + * Set the recovery Azure storage account. + * + * @param recoveryAzureStorageAccount the recoveryAzureStorageAccount value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withRecoveryAzureStorageAccount(String recoveryAzureStorageAccount) { + this.recoveryAzureStorageAccount = recoveryAzureStorageAccount; + return this; + } + + /** + * Get the ARM id of the log storage account used for replication. This will be set to null if no log storage account was provided during enable protection. + * + * @return the recoveryAzureLogStorageAccountId value + */ + public String recoveryAzureLogStorageAccountId() { + return this.recoveryAzureLogStorageAccountId; + } + + /** + * Set the ARM id of the log storage account used for replication. This will be set to null if no log storage account was provided during enable protection. + * + * @param recoveryAzureLogStorageAccountId the recoveryAzureLogStorageAccountId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withRecoveryAzureLogStorageAccountId(String recoveryAzureLogStorageAccountId) { + this.recoveryAzureLogStorageAccountId = recoveryAzureLogStorageAccountId; + return this; + } + + /** + * Get the PE Network details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the PE Network details. + * + * @param vmNics the vmNics value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get the selected recovery azure network Id. + * + * @return the selectedRecoveryAzureNetworkId value + */ + public String selectedRecoveryAzureNetworkId() { + return this.selectedRecoveryAzureNetworkId; + } + + /** + * Set the selected recovery azure network Id. + * + * @param selectedRecoveryAzureNetworkId the selectedRecoveryAzureNetworkId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withSelectedRecoveryAzureNetworkId(String selectedRecoveryAzureNetworkId) { + this.selectedRecoveryAzureNetworkId = selectedRecoveryAzureNetworkId; + return this; + } + + /** + * Get the selected source nic Id which will be used as the primary nic during failover. + * + * @return the selectedSourceNicId value + */ + public String selectedSourceNicId() { + return this.selectedSourceNicId; + } + + /** + * Set the selected source nic Id which will be used as the primary nic during failover. + * + * @param selectedSourceNicId the selectedSourceNicId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withSelectedSourceNicId(String selectedSourceNicId) { + this.selectedSourceNicId = selectedSourceNicId; + return this; + } + + /** + * Get a value indicating the discovery type of the machine. Value can be vCenter or physical. + * + * @return the discoveryType value + */ + public String discoveryType() { + return this.discoveryType; + } + + /** + * Set a value indicating the discovery type of the machine. Value can be vCenter or physical. + * + * @param discoveryType the discoveryType value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withDiscoveryType(String discoveryType) { + this.discoveryType = discoveryType; + return this; + } + + /** + * Get the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @return the enableRdpOnTargetOption value + */ + public String enableRdpOnTargetOption() { + return this.enableRdpOnTargetOption; + } + + /** + * Set the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @param enableRdpOnTargetOption the enableRdpOnTargetOption value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withEnableRdpOnTargetOption(String enableRdpOnTargetOption) { + this.enableRdpOnTargetOption = enableRdpOnTargetOption; + return this; + } + + /** + * Get the data stores of the on-premise machine. Value can be list of strings that contain data store names. + * + * @return the datastores value + */ + public List datastores() { + return this.datastores; + } + + /** + * Set the data stores of the on-premise machine. Value can be list of strings that contain data store names. + * + * @param datastores the datastores value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withDatastores(List datastores) { + this.datastores = datastores; + return this; + } + + /** + * Get the ARM Id of the target Azure VM. This value will be null until the VM is failed over. Only after failure it will be populated with the ARM Id of the Azure VM. + * + * @return the targetVmId value + */ + public String targetVmId() { + return this.targetVmId; + } + + /** + * Set the ARM Id of the target Azure VM. This value will be null until the VM is failed over. Only after failure it will be populated with the ARM Id of the Azure VM. + * + * @param targetVmId the targetVmId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withTargetVmId(String targetVmId) { + this.targetVmId = targetVmId; + return this; + } + + /** + * Get the target resource group Id. + * + * @return the recoveryAzureResourceGroupId value + */ + public String recoveryAzureResourceGroupId() { + return this.recoveryAzureResourceGroupId; + } + + /** + * Set the target resource group Id. + * + * @param recoveryAzureResourceGroupId the recoveryAzureResourceGroupId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withRecoveryAzureResourceGroupId(String recoveryAzureResourceGroupId) { + this.recoveryAzureResourceGroupId = recoveryAzureResourceGroupId; + return this; + } + + /** + * Get the recovery availability set Id. + * + * @return the recoveryAvailabilitySetId value + */ + public String recoveryAvailabilitySetId() { + return this.recoveryAvailabilitySetId; + } + + /** + * Set the recovery availability set Id. + * + * @param recoveryAvailabilitySetId the recoveryAvailabilitySetId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withRecoveryAvailabilitySetId(String recoveryAvailabilitySetId) { + this.recoveryAvailabilitySetId = recoveryAvailabilitySetId; + return this; + } + + /** + * Get a value indicating whether managed disks should be used during failover. + * + * @return the useManagedDisks value + */ + public String useManagedDisks() { + return this.useManagedDisks; + } + + /** + * Set a value indicating whether managed disks should be used during failover. + * + * @param useManagedDisks the useManagedDisks value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withUseManagedDisks(String useManagedDisks) { + this.useManagedDisks = useManagedDisks; + return this; + } + + /** + * Get license Type of the VM to be used. + * + * @return the licenseType value + */ + public String licenseType() { + return this.licenseType; + } + + /** + * Set license Type of the VM to be used. + * + * @param licenseType the licenseType value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withLicenseType(String licenseType) { + this.licenseType = licenseType; + return this; + } + + /** + * Get the validation errors of the on-premise machine Value can be list of validation errors. + * + * @return the validationErrors value + */ + public List validationErrors() { + return this.validationErrors; + } + + /** + * Set the validation errors of the on-premise machine Value can be list of validation errors. + * + * @param validationErrors the validationErrors value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withValidationErrors(List validationErrors) { + this.validationErrors = validationErrors; + return this; + } + + /** + * Get the last RPO calculated time. + * + * @return the lastRpoCalculatedTime value + */ + public DateTime lastRpoCalculatedTime() { + return this.lastRpoCalculatedTime; + } + + /** + * Set the last RPO calculated time. + * + * @param lastRpoCalculatedTime the lastRpoCalculatedTime value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withLastRpoCalculatedTime(DateTime lastRpoCalculatedTime) { + this.lastRpoCalculatedTime = lastRpoCalculatedTime; + return this; + } + + /** + * Get the last update time received from on-prem components. + * + * @return the lastUpdateReceivedTime value + */ + public DateTime lastUpdateReceivedTime() { + return this.lastUpdateReceivedTime; + } + + /** + * Set the last update time received from on-prem components. + * + * @param lastUpdateReceivedTime the lastUpdateReceivedTime value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withLastUpdateReceivedTime(DateTime lastUpdateReceivedTime) { + this.lastUpdateReceivedTime = lastUpdateReceivedTime; + return this; + } + + /** + * Get the replica id of the protected item. + * + * @return the replicaId value + */ + public String replicaId() { + return this.replicaId; + } + + /** + * Set the replica id of the protected item. + * + * @param replicaId the replicaId value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withReplicaId(String replicaId) { + this.replicaId = replicaId; + return this; + } + + /** + * Get the OS Version of the protected item. + * + * @return the osVersion value + */ + public String osVersion() { + return this.osVersion; + } + + /** + * Set the OS Version of the protected item. + * + * @param osVersion the osVersion value to set + * @return the InMageAzureV2ReplicationDetails object itself. + */ + public InMageAzureV2ReplicationDetails withOsVersion(String osVersion) { + this.osVersion = osVersion; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ReprotectInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ReprotectInput.java new file mode 100644 index 0000000000000..d42db36682298 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2ReprotectInput.java @@ -0,0 +1,204 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMageAzureV2 specific provider input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2ReprotectInput extends ReverseReplicationProviderSpecificInput { + /** + * The Master target Id. + */ + @JsonProperty(value = "masterTargetId") + private String masterTargetId; + + /** + * The Process Server Id. + */ + @JsonProperty(value = "processServerId") + private String processServerId; + + /** + * The storage account id. + */ + @JsonProperty(value = "storageAccountId") + private String storageAccountId; + + /** + * The CS account Id. + */ + @JsonProperty(value = "runAsAccountId") + private String runAsAccountId; + + /** + * The Policy Id. + */ + @JsonProperty(value = "policyId") + private String policyId; + + /** + * The storage account to be used for logging during replication. + */ + @JsonProperty(value = "logStorageAccountId") + private String logStorageAccountId; + + /** + * The disks to include list. + */ + @JsonProperty(value = "disksToInclude") + private List disksToInclude; + + /** + * Get the Master target Id. + * + * @return the masterTargetId value + */ + public String masterTargetId() { + return this.masterTargetId; + } + + /** + * Set the Master target Id. + * + * @param masterTargetId the masterTargetId value to set + * @return the InMageAzureV2ReprotectInput object itself. + */ + public InMageAzureV2ReprotectInput withMasterTargetId(String masterTargetId) { + this.masterTargetId = masterTargetId; + return this; + } + + /** + * Get the Process Server Id. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the Process Server Id. + * + * @param processServerId the processServerId value to set + * @return the InMageAzureV2ReprotectInput object itself. + */ + public InMageAzureV2ReprotectInput withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the storage account id. + * + * @return the storageAccountId value + */ + public String storageAccountId() { + return this.storageAccountId; + } + + /** + * Set the storage account id. + * + * @param storageAccountId the storageAccountId value to set + * @return the InMageAzureV2ReprotectInput object itself. + */ + public InMageAzureV2ReprotectInput withStorageAccountId(String storageAccountId) { + this.storageAccountId = storageAccountId; + return this; + } + + /** + * Get the CS account Id. + * + * @return the runAsAccountId value + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Set the CS account Id. + * + * @param runAsAccountId the runAsAccountId value to set + * @return the InMageAzureV2ReprotectInput object itself. + */ + public InMageAzureV2ReprotectInput withRunAsAccountId(String runAsAccountId) { + this.runAsAccountId = runAsAccountId; + return this; + } + + /** + * Get the Policy Id. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Set the Policy Id. + * + * @param policyId the policyId value to set + * @return the InMageAzureV2ReprotectInput object itself. + */ + public InMageAzureV2ReprotectInput withPolicyId(String policyId) { + this.policyId = policyId; + return this; + } + + /** + * Get the storage account to be used for logging during replication. + * + * @return the logStorageAccountId value + */ + public String logStorageAccountId() { + return this.logStorageAccountId; + } + + /** + * Set the storage account to be used for logging during replication. + * + * @param logStorageAccountId the logStorageAccountId value to set + * @return the InMageAzureV2ReprotectInput object itself. + */ + public InMageAzureV2ReprotectInput withLogStorageAccountId(String logStorageAccountId) { + this.logStorageAccountId = logStorageAccountId; + return this; + } + + /** + * Get the disks to include list. + * + * @return the disksToInclude value + */ + public List disksToInclude() { + return this.disksToInclude; + } + + /** + * Set the disks to include list. + * + * @param disksToInclude the disksToInclude value to set + * @return the InMageAzureV2ReprotectInput object itself. + */ + public InMageAzureV2ReprotectInput withDisksToInclude(List disksToInclude) { + this.disksToInclude = disksToInclude; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2UpdateReplicationProtectedItemInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2UpdateReplicationProtectedItemInput.java new file mode 100644 index 0000000000000..0b84bb25690ef --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageAzureV2UpdateReplicationProtectedItemInput.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMage Azure V2 input to update replication protected item. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class InMageAzureV2UpdateReplicationProtectedItemInput extends UpdateReplicationProtectedItemProviderInput { + /** + * The recovery Azure resource group Id for classic deployment. + */ + @JsonProperty(value = "recoveryAzureV1ResourceGroupId") + private String recoveryAzureV1ResourceGroupId; + + /** + * The recovery Azure resource group Id for resource manager deployment. + */ + @JsonProperty(value = "recoveryAzureV2ResourceGroupId") + private String recoveryAzureV2ResourceGroupId; + + /** + * A value indicating whether managed disks should be used during failover. + */ + @JsonProperty(value = "useManagedDisks") + private String useManagedDisks; + + /** + * Get the recovery Azure resource group Id for classic deployment. + * + * @return the recoveryAzureV1ResourceGroupId value + */ + public String recoveryAzureV1ResourceGroupId() { + return this.recoveryAzureV1ResourceGroupId; + } + + /** + * Set the recovery Azure resource group Id for classic deployment. + * + * @param recoveryAzureV1ResourceGroupId the recoveryAzureV1ResourceGroupId value to set + * @return the InMageAzureV2UpdateReplicationProtectedItemInput object itself. + */ + public InMageAzureV2UpdateReplicationProtectedItemInput withRecoveryAzureV1ResourceGroupId(String recoveryAzureV1ResourceGroupId) { + this.recoveryAzureV1ResourceGroupId = recoveryAzureV1ResourceGroupId; + return this; + } + + /** + * Get the recovery Azure resource group Id for resource manager deployment. + * + * @return the recoveryAzureV2ResourceGroupId value + */ + public String recoveryAzureV2ResourceGroupId() { + return this.recoveryAzureV2ResourceGroupId; + } + + /** + * Set the recovery Azure resource group Id for resource manager deployment. + * + * @param recoveryAzureV2ResourceGroupId the recoveryAzureV2ResourceGroupId value to set + * @return the InMageAzureV2UpdateReplicationProtectedItemInput object itself. + */ + public InMageAzureV2UpdateReplicationProtectedItemInput withRecoveryAzureV2ResourceGroupId(String recoveryAzureV2ResourceGroupId) { + this.recoveryAzureV2ResourceGroupId = recoveryAzureV2ResourceGroupId; + return this; + } + + /** + * Get a value indicating whether managed disks should be used during failover. + * + * @return the useManagedDisks value + */ + public String useManagedDisks() { + return this.useManagedDisks; + } + + /** + * Set a value indicating whether managed disks should be used during failover. + * + * @param useManagedDisks the useManagedDisks value to set + * @return the InMageAzureV2UpdateReplicationProtectedItemInput object itself. + */ + public InMageAzureV2UpdateReplicationProtectedItemInput withUseManagedDisks(String useManagedDisks) { + this.useManagedDisks = useManagedDisks; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageBasePolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageBasePolicyDetails.java new file mode 100644 index 0000000000000..67d655ec8ad3d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageBasePolicyDetails.java @@ -0,0 +1,126 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Base class for the policies of providers using InMage replication. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageBasePolicyDetails") +public class InMageBasePolicyDetails extends PolicyProviderSpecificDetails { + /** + * The recovery point threshold in minutes. + */ + @JsonProperty(value = "recoveryPointThresholdInMinutes") + private Integer recoveryPointThresholdInMinutes; + + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistory") + private Integer recoveryPointHistory; + + /** + * The app consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * A value indicating whether multi-VM sync has to be enabled. + */ + @JsonProperty(value = "multiVmSyncStatus") + private String multiVmSyncStatus; + + /** + * Get the recovery point threshold in minutes. + * + * @return the recoveryPointThresholdInMinutes value + */ + public Integer recoveryPointThresholdInMinutes() { + return this.recoveryPointThresholdInMinutes; + } + + /** + * Set the recovery point threshold in minutes. + * + * @param recoveryPointThresholdInMinutes the recoveryPointThresholdInMinutes value to set + * @return the InMageBasePolicyDetails object itself. + */ + public InMageBasePolicyDetails withRecoveryPointThresholdInMinutes(Integer recoveryPointThresholdInMinutes) { + this.recoveryPointThresholdInMinutes = recoveryPointThresholdInMinutes; + return this; + } + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistory value + */ + public Integer recoveryPointHistory() { + return this.recoveryPointHistory; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistory the recoveryPointHistory value to set + * @return the InMageBasePolicyDetails object itself. + */ + public InMageBasePolicyDetails withRecoveryPointHistory(Integer recoveryPointHistory) { + this.recoveryPointHistory = recoveryPointHistory; + return this; + } + + /** + * Get the app consistent snapshot frequency in minutes. + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency in minutes. + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the InMageBasePolicyDetails object itself. + */ + public InMageBasePolicyDetails withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get a value indicating whether multi-VM sync has to be enabled. + * + * @return the multiVmSyncStatus value + */ + public String multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi-VM sync has to be enabled. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the InMageBasePolicyDetails object itself. + */ + public InMageBasePolicyDetails withMultiVmSyncStatus(String multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDisableProtectionProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDisableProtectionProviderSpecificInput.java new file mode 100644 index 0000000000000..413e3798b63cc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDisableProtectionProviderSpecificInput.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMage disable protection provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMage") +public class InMageDisableProtectionProviderSpecificInput extends DisableProtectionProviderSpecificInput { + /** + * A value indicating whether the replica VM should be destroyed or + * retained. Values from Delete and Retain. + */ + @JsonProperty(value = "replicaVmDeletionStatus") + private String replicaVmDeletionStatus; + + /** + * Get a value indicating whether the replica VM should be destroyed or retained. Values from Delete and Retain. + * + * @return the replicaVmDeletionStatus value + */ + public String replicaVmDeletionStatus() { + return this.replicaVmDeletionStatus; + } + + /** + * Set a value indicating whether the replica VM should be destroyed or retained. Values from Delete and Retain. + * + * @param replicaVmDeletionStatus the replicaVmDeletionStatus value to set + * @return the InMageDisableProtectionProviderSpecificInput object itself. + */ + public InMageDisableProtectionProviderSpecificInput withReplicaVmDeletionStatus(String replicaVmDeletionStatus) { + this.replicaVmDeletionStatus = replicaVmDeletionStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskDetails.java new file mode 100644 index 0000000000000..059f1693733e1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskDetails.java @@ -0,0 +1,174 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * VMware/Physical specific Disk Details. + */ +public class InMageDiskDetails { + /** + * The disk Id. + */ + @JsonProperty(value = "diskId") + private String diskId; + + /** + * The disk name. + */ + @JsonProperty(value = "diskName") + private String diskName; + + /** + * The disk size in MB. + */ + @JsonProperty(value = "diskSizeInMB") + private String diskSizeInMB; + + /** + * Whether disk is system disk or data disk. + */ + @JsonProperty(value = "diskType") + private String diskType; + + /** + * Whether disk is dynamic disk or basic disk. + */ + @JsonProperty(value = "diskConfiguration") + private String diskConfiguration; + + /** + * Volumes of the disk. + */ + @JsonProperty(value = "volumeList") + private List volumeList; + + /** + * Get the disk Id. + * + * @return the diskId value + */ + public String diskId() { + return this.diskId; + } + + /** + * Set the disk Id. + * + * @param diskId the diskId value to set + * @return the InMageDiskDetails object itself. + */ + public InMageDiskDetails withDiskId(String diskId) { + this.diskId = diskId; + return this; + } + + /** + * Get the disk name. + * + * @return the diskName value + */ + public String diskName() { + return this.diskName; + } + + /** + * Set the disk name. + * + * @param diskName the diskName value to set + * @return the InMageDiskDetails object itself. + */ + public InMageDiskDetails withDiskName(String diskName) { + this.diskName = diskName; + return this; + } + + /** + * Get the disk size in MB. + * + * @return the diskSizeInMB value + */ + public String diskSizeInMB() { + return this.diskSizeInMB; + } + + /** + * Set the disk size in MB. + * + * @param diskSizeInMB the diskSizeInMB value to set + * @return the InMageDiskDetails object itself. + */ + public InMageDiskDetails withDiskSizeInMB(String diskSizeInMB) { + this.diskSizeInMB = diskSizeInMB; + return this; + } + + /** + * Get whether disk is system disk or data disk. + * + * @return the diskType value + */ + public String diskType() { + return this.diskType; + } + + /** + * Set whether disk is system disk or data disk. + * + * @param diskType the diskType value to set + * @return the InMageDiskDetails object itself. + */ + public InMageDiskDetails withDiskType(String diskType) { + this.diskType = diskType; + return this; + } + + /** + * Get whether disk is dynamic disk or basic disk. + * + * @return the diskConfiguration value + */ + public String diskConfiguration() { + return this.diskConfiguration; + } + + /** + * Set whether disk is dynamic disk or basic disk. + * + * @param diskConfiguration the diskConfiguration value to set + * @return the InMageDiskDetails object itself. + */ + public InMageDiskDetails withDiskConfiguration(String diskConfiguration) { + this.diskConfiguration = diskConfiguration; + return this; + } + + /** + * Get volumes of the disk. + * + * @return the volumeList value + */ + public List volumeList() { + return this.volumeList; + } + + /** + * Set volumes of the disk. + * + * @param volumeList the volumeList value to set + * @return the InMageDiskDetails object itself. + */ + public InMageDiskDetails withVolumeList(List volumeList) { + this.volumeList = volumeList; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskExclusionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskExclusionInput.java new file mode 100644 index 0000000000000..de3abbf14afbb --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskExclusionInput.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * DiskExclusionInput when doing enable protection of virtual machine in InMage + * provider. + */ +public class InMageDiskExclusionInput { + /** + * The volume label based option for disk exclusion. + */ + @JsonProperty(value = "volumeOptions") + private List volumeOptions; + + /** + * The guest disk signature based option for disk exclusion. + */ + @JsonProperty(value = "diskSignatureOptions") + private List diskSignatureOptions; + + /** + * Get the volume label based option for disk exclusion. + * + * @return the volumeOptions value + */ + public List volumeOptions() { + return this.volumeOptions; + } + + /** + * Set the volume label based option for disk exclusion. + * + * @param volumeOptions the volumeOptions value to set + * @return the InMageDiskExclusionInput object itself. + */ + public InMageDiskExclusionInput withVolumeOptions(List volumeOptions) { + this.volumeOptions = volumeOptions; + return this; + } + + /** + * Get the guest disk signature based option for disk exclusion. + * + * @return the diskSignatureOptions value + */ + public List diskSignatureOptions() { + return this.diskSignatureOptions; + } + + /** + * Set the guest disk signature based option for disk exclusion. + * + * @param diskSignatureOptions the diskSignatureOptions value to set + * @return the InMageDiskExclusionInput object itself. + */ + public InMageDiskExclusionInput withDiskSignatureOptions(List diskSignatureOptions) { + this.diskSignatureOptions = diskSignatureOptions; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskSignatureExclusionOptions.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskSignatureExclusionOptions.java new file mode 100644 index 0000000000000..2b8f43356709f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageDiskSignatureExclusionOptions.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Guest disk signature based disk exclusion option when doing enable + * protection of virtual machine in InMage provider. + */ +public class InMageDiskSignatureExclusionOptions { + /** + * The guest signature of disk to be excluded from replication. + */ + @JsonProperty(value = "diskSignature") + private String diskSignature; + + /** + * Get the guest signature of disk to be excluded from replication. + * + * @return the diskSignature value + */ + public String diskSignature() { + return this.diskSignature; + } + + /** + * Set the guest signature of disk to be excluded from replication. + * + * @param diskSignature the diskSignature value to set + * @return the InMageDiskSignatureExclusionOptions object itself. + */ + public InMageDiskSignatureExclusionOptions withDiskSignature(String diskSignature) { + this.diskSignature = diskSignature; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageEnableProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageEnableProtectionInput.java new file mode 100644 index 0000000000000..dc1c768fba3e8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageEnableProtectionInput.java @@ -0,0 +1,282 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMware Azure specific enable protection input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMage") +public class InMageEnableProtectionInput extends EnableProtectionProviderSpecificInput { + /** + * The Vm Name. + */ + @JsonProperty(value = "vmFriendlyName") + private String vmFriendlyName; + + /** + * The Master Target Id. + */ + @JsonProperty(value = "masterTargetId", required = true) + private String masterTargetId; + + /** + * The Process Server Id. + */ + @JsonProperty(value = "processServerId", required = true) + private String processServerId; + + /** + * The retention drive to use on the MT. + */ + @JsonProperty(value = "retentionDrive", required = true) + private String retentionDrive; + + /** + * The CS account Id. + */ + @JsonProperty(value = "runAsAccountId") + private String runAsAccountId; + + /** + * The multi vm group Id. + */ + @JsonProperty(value = "multiVmGroupId", required = true) + private String multiVmGroupId; + + /** + * The multi vm group name. + */ + @JsonProperty(value = "multiVmGroupName", required = true) + private String multiVmGroupName; + + /** + * The target data store name. + */ + @JsonProperty(value = "datastoreName") + private String datastoreName; + + /** + * The enable disk exclusion input. + */ + @JsonProperty(value = "diskExclusionInput") + private InMageDiskExclusionInput diskExclusionInput; + + /** + * The disks to include list. + */ + @JsonProperty(value = "disksToInclude") + private List disksToInclude; + + /** + * Get the Vm Name. + * + * @return the vmFriendlyName value + */ + public String vmFriendlyName() { + return this.vmFriendlyName; + } + + /** + * Set the Vm Name. + * + * @param vmFriendlyName the vmFriendlyName value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withVmFriendlyName(String vmFriendlyName) { + this.vmFriendlyName = vmFriendlyName; + return this; + } + + /** + * Get the Master Target Id. + * + * @return the masterTargetId value + */ + public String masterTargetId() { + return this.masterTargetId; + } + + /** + * Set the Master Target Id. + * + * @param masterTargetId the masterTargetId value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withMasterTargetId(String masterTargetId) { + this.masterTargetId = masterTargetId; + return this; + } + + /** + * Get the Process Server Id. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the Process Server Id. + * + * @param processServerId the processServerId value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the retention drive to use on the MT. + * + * @return the retentionDrive value + */ + public String retentionDrive() { + return this.retentionDrive; + } + + /** + * Set the retention drive to use on the MT. + * + * @param retentionDrive the retentionDrive value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withRetentionDrive(String retentionDrive) { + this.retentionDrive = retentionDrive; + return this; + } + + /** + * Get the CS account Id. + * + * @return the runAsAccountId value + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Set the CS account Id. + * + * @param runAsAccountId the runAsAccountId value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withRunAsAccountId(String runAsAccountId) { + this.runAsAccountId = runAsAccountId; + return this; + } + + /** + * Get the multi vm group Id. + * + * @return the multiVmGroupId value + */ + public String multiVmGroupId() { + return this.multiVmGroupId; + } + + /** + * Set the multi vm group Id. + * + * @param multiVmGroupId the multiVmGroupId value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withMultiVmGroupId(String multiVmGroupId) { + this.multiVmGroupId = multiVmGroupId; + return this; + } + + /** + * Get the multi vm group name. + * + * @return the multiVmGroupName value + */ + public String multiVmGroupName() { + return this.multiVmGroupName; + } + + /** + * Set the multi vm group name. + * + * @param multiVmGroupName the multiVmGroupName value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withMultiVmGroupName(String multiVmGroupName) { + this.multiVmGroupName = multiVmGroupName; + return this; + } + + /** + * Get the target data store name. + * + * @return the datastoreName value + */ + public String datastoreName() { + return this.datastoreName; + } + + /** + * Set the target data store name. + * + * @param datastoreName the datastoreName value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withDatastoreName(String datastoreName) { + this.datastoreName = datastoreName; + return this; + } + + /** + * Get the enable disk exclusion input. + * + * @return the diskExclusionInput value + */ + public InMageDiskExclusionInput diskExclusionInput() { + return this.diskExclusionInput; + } + + /** + * Set the enable disk exclusion input. + * + * @param diskExclusionInput the diskExclusionInput value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withDiskExclusionInput(InMageDiskExclusionInput diskExclusionInput) { + this.diskExclusionInput = diskExclusionInput; + return this; + } + + /** + * Get the disks to include list. + * + * @return the disksToInclude value + */ + public List disksToInclude() { + return this.disksToInclude; + } + + /** + * Set the disks to include list. + * + * @param disksToInclude the disksToInclude value to set + * @return the InMageEnableProtectionInput object itself. + */ + public InMageEnableProtectionInput withDisksToInclude(List disksToInclude) { + this.disksToInclude = disksToInclude; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageFailoverProviderInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageFailoverProviderInput.java new file mode 100644 index 0000000000000..6d0bacb5053a9 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageFailoverProviderInput.java @@ -0,0 +1,77 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Provider specific input for InMage failover. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMage") +public class InMageFailoverProviderInput extends ProviderSpecificFailoverInput { + /** + * The recovery point type. Values from LatestTime, LatestTag or Custom. In + * the case of custom, the recovery point provided by RecoveryPointId will + * be used. In the other two cases, recovery point id will be ignored. + * Possible values include: 'LatestTime', 'LatestTag', 'Custom'. + */ + @JsonProperty(value = "recoveryPointType") + private RecoveryPointType recoveryPointType; + + /** + * The recovery point id to be passed to failover to a particular recovery + * point. In case of latest recovery point, null should be passed. + */ + @JsonProperty(value = "recoveryPointId") + private String recoveryPointId; + + /** + * Get the recovery point type. Values from LatestTime, LatestTag or Custom. In the case of custom, the recovery point provided by RecoveryPointId will be used. In the other two cases, recovery point id will be ignored. Possible values include: 'LatestTime', 'LatestTag', 'Custom'. + * + * @return the recoveryPointType value + */ + public RecoveryPointType recoveryPointType() { + return this.recoveryPointType; + } + + /** + * Set the recovery point type. Values from LatestTime, LatestTag or Custom. In the case of custom, the recovery point provided by RecoveryPointId will be used. In the other two cases, recovery point id will be ignored. Possible values include: 'LatestTime', 'LatestTag', 'Custom'. + * + * @param recoveryPointType the recoveryPointType value to set + * @return the InMageFailoverProviderInput object itself. + */ + public InMageFailoverProviderInput withRecoveryPointType(RecoveryPointType recoveryPointType) { + this.recoveryPointType = recoveryPointType; + return this; + } + + /** + * Get the recovery point id to be passed to failover to a particular recovery point. In case of latest recovery point, null should be passed. + * + * @return the recoveryPointId value + */ + public String recoveryPointId() { + return this.recoveryPointId; + } + + /** + * Set the recovery point id to be passed to failover to a particular recovery point. In case of latest recovery point, null should be passed. + * + * @param recoveryPointId the recoveryPointId value to set + * @return the InMageFailoverProviderInput object itself. + */ + public InMageFailoverProviderInput withRecoveryPointId(String recoveryPointId) { + this.recoveryPointId = recoveryPointId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMagePolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMagePolicyDetails.java new file mode 100644 index 0000000000000..0a949924c4946 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMagePolicyDetails.java @@ -0,0 +1,126 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMage specific protection profile details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMage") +public class InMagePolicyDetails extends PolicyProviderSpecificDetails { + /** + * The recovery point threshold in minutes. + */ + @JsonProperty(value = "recoveryPointThresholdInMinutes") + private Integer recoveryPointThresholdInMinutes; + + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistory") + private Integer recoveryPointHistory; + + /** + * The app consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * A value indicating whether multi-VM sync has to be enabled. + */ + @JsonProperty(value = "multiVmSyncStatus") + private String multiVmSyncStatus; + + /** + * Get the recovery point threshold in minutes. + * + * @return the recoveryPointThresholdInMinutes value + */ + public Integer recoveryPointThresholdInMinutes() { + return this.recoveryPointThresholdInMinutes; + } + + /** + * Set the recovery point threshold in minutes. + * + * @param recoveryPointThresholdInMinutes the recoveryPointThresholdInMinutes value to set + * @return the InMagePolicyDetails object itself. + */ + public InMagePolicyDetails withRecoveryPointThresholdInMinutes(Integer recoveryPointThresholdInMinutes) { + this.recoveryPointThresholdInMinutes = recoveryPointThresholdInMinutes; + return this; + } + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistory value + */ + public Integer recoveryPointHistory() { + return this.recoveryPointHistory; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistory the recoveryPointHistory value to set + * @return the InMagePolicyDetails object itself. + */ + public InMagePolicyDetails withRecoveryPointHistory(Integer recoveryPointHistory) { + this.recoveryPointHistory = recoveryPointHistory; + return this; + } + + /** + * Get the app consistent snapshot frequency in minutes. + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency in minutes. + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the InMagePolicyDetails object itself. + */ + public InMagePolicyDetails withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get a value indicating whether multi-VM sync has to be enabled. + * + * @return the multiVmSyncStatus value + */ + public String multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi-VM sync has to be enabled. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the InMagePolicyDetails object itself. + */ + public InMagePolicyDetails withMultiVmSyncStatus(String multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMagePolicyInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMagePolicyInput.java new file mode 100644 index 0000000000000..6fbc1834af9cf --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMagePolicyInput.java @@ -0,0 +1,128 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMWare Azure specific protection profile Input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMage") +public class InMagePolicyInput extends PolicyProviderSpecificInput { + /** + * The recovery point threshold in minutes. + */ + @JsonProperty(value = "recoveryPointThresholdInMinutes") + private Integer recoveryPointThresholdInMinutes; + + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistory") + private Integer recoveryPointHistory; + + /** + * The app consistent snapshot frequency (in minutes). + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * A value indicating whether multi-VM sync has to be enabled. Value should + * be 'Enabled' or 'Disabled'. Possible values include: 'Enable', + * 'Disable'. + */ + @JsonProperty(value = "multiVmSyncStatus", required = true) + private SetMultiVmSyncStatus multiVmSyncStatus; + + /** + * Get the recovery point threshold in minutes. + * + * @return the recoveryPointThresholdInMinutes value + */ + public Integer recoveryPointThresholdInMinutes() { + return this.recoveryPointThresholdInMinutes; + } + + /** + * Set the recovery point threshold in minutes. + * + * @param recoveryPointThresholdInMinutes the recoveryPointThresholdInMinutes value to set + * @return the InMagePolicyInput object itself. + */ + public InMagePolicyInput withRecoveryPointThresholdInMinutes(Integer recoveryPointThresholdInMinutes) { + this.recoveryPointThresholdInMinutes = recoveryPointThresholdInMinutes; + return this; + } + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistory value + */ + public Integer recoveryPointHistory() { + return this.recoveryPointHistory; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistory the recoveryPointHistory value to set + * @return the InMagePolicyInput object itself. + */ + public InMagePolicyInput withRecoveryPointHistory(Integer recoveryPointHistory) { + this.recoveryPointHistory = recoveryPointHistory; + return this; + } + + /** + * Get the app consistent snapshot frequency (in minutes). + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency (in minutes). + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the InMagePolicyInput object itself. + */ + public InMagePolicyInput withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get a value indicating whether multi-VM sync has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values include: 'Enable', 'Disable'. + * + * @return the multiVmSyncStatus value + */ + public SetMultiVmSyncStatus multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi-VM sync has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values include: 'Enable', 'Disable'. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the InMagePolicyInput object itself. + */ + public InMagePolicyInput withMultiVmSyncStatus(SetMultiVmSyncStatus multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageProtectedDiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageProtectedDiskDetails.java new file mode 100644 index 0000000000000..d78960aa05d17 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageProtectedDiskDetails.java @@ -0,0 +1,408 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * InMage protected disk details. + */ +public class InMageProtectedDiskDetails { + /** + * The disk id. + */ + @JsonProperty(value = "diskId") + private String diskId; + + /** + * The disk name. + */ + @JsonProperty(value = "diskName") + private String diskName; + + /** + * The protection stage. + */ + @JsonProperty(value = "protectionStage") + private String protectionStage; + + /** + * The health error code for the disk. + */ + @JsonProperty(value = "healthErrorCode") + private String healthErrorCode; + + /** + * The RPO in seconds. + */ + @JsonProperty(value = "rpoInSeconds") + private Long rpoInSeconds; + + /** + * A value indicating whether resync is required for this disk. + */ + @JsonProperty(value = "resyncRequired") + private String resyncRequired; + + /** + * The resync progress percentage. + */ + @JsonProperty(value = "resyncProgressPercentage") + private Integer resyncProgressPercentage; + + /** + * The resync duration in seconds. + */ + @JsonProperty(value = "resyncDurationInSeconds") + private Long resyncDurationInSeconds; + + /** + * The disk capacity in bytes. + */ + @JsonProperty(value = "diskCapacityInBytes") + private Long diskCapacityInBytes; + + /** + * The file system capacity in bytes. + */ + @JsonProperty(value = "fileSystemCapacityInBytes") + private Long fileSystemCapacityInBytes; + + /** + * The source data transit in MB. + */ + @JsonProperty(value = "sourceDataInMB") + private Double sourceDataInMB; + + /** + * The PS data transit in MB. + */ + @JsonProperty(value = "psDataInMB") + private Double psDataInMB; + + /** + * The target data transit in MB. + */ + @JsonProperty(value = "targetDataInMB") + private Double targetDataInMB; + + /** + * A value indicating whether disk is resized. + */ + @JsonProperty(value = "diskResized") + private String diskResized; + + /** + * The last RPO calculated time. + */ + @JsonProperty(value = "lastRpoCalculatedTime") + private DateTime lastRpoCalculatedTime; + + /** + * Get the disk id. + * + * @return the diskId value + */ + public String diskId() { + return this.diskId; + } + + /** + * Set the disk id. + * + * @param diskId the diskId value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withDiskId(String diskId) { + this.diskId = diskId; + return this; + } + + /** + * Get the disk name. + * + * @return the diskName value + */ + public String diskName() { + return this.diskName; + } + + /** + * Set the disk name. + * + * @param diskName the diskName value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withDiskName(String diskName) { + this.diskName = diskName; + return this; + } + + /** + * Get the protection stage. + * + * @return the protectionStage value + */ + public String protectionStage() { + return this.protectionStage; + } + + /** + * Set the protection stage. + * + * @param protectionStage the protectionStage value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withProtectionStage(String protectionStage) { + this.protectionStage = protectionStage; + return this; + } + + /** + * Get the health error code for the disk. + * + * @return the healthErrorCode value + */ + public String healthErrorCode() { + return this.healthErrorCode; + } + + /** + * Set the health error code for the disk. + * + * @param healthErrorCode the healthErrorCode value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withHealthErrorCode(String healthErrorCode) { + this.healthErrorCode = healthErrorCode; + return this; + } + + /** + * Get the RPO in seconds. + * + * @return the rpoInSeconds value + */ + public Long rpoInSeconds() { + return this.rpoInSeconds; + } + + /** + * Set the RPO in seconds. + * + * @param rpoInSeconds the rpoInSeconds value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withRpoInSeconds(Long rpoInSeconds) { + this.rpoInSeconds = rpoInSeconds; + return this; + } + + /** + * Get a value indicating whether resync is required for this disk. + * + * @return the resyncRequired value + */ + public String resyncRequired() { + return this.resyncRequired; + } + + /** + * Set a value indicating whether resync is required for this disk. + * + * @param resyncRequired the resyncRequired value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withResyncRequired(String resyncRequired) { + this.resyncRequired = resyncRequired; + return this; + } + + /** + * Get the resync progress percentage. + * + * @return the resyncProgressPercentage value + */ + public Integer resyncProgressPercentage() { + return this.resyncProgressPercentage; + } + + /** + * Set the resync progress percentage. + * + * @param resyncProgressPercentage the resyncProgressPercentage value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withResyncProgressPercentage(Integer resyncProgressPercentage) { + this.resyncProgressPercentage = resyncProgressPercentage; + return this; + } + + /** + * Get the resync duration in seconds. + * + * @return the resyncDurationInSeconds value + */ + public Long resyncDurationInSeconds() { + return this.resyncDurationInSeconds; + } + + /** + * Set the resync duration in seconds. + * + * @param resyncDurationInSeconds the resyncDurationInSeconds value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withResyncDurationInSeconds(Long resyncDurationInSeconds) { + this.resyncDurationInSeconds = resyncDurationInSeconds; + return this; + } + + /** + * Get the disk capacity in bytes. + * + * @return the diskCapacityInBytes value + */ + public Long diskCapacityInBytes() { + return this.diskCapacityInBytes; + } + + /** + * Set the disk capacity in bytes. + * + * @param diskCapacityInBytes the diskCapacityInBytes value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withDiskCapacityInBytes(Long diskCapacityInBytes) { + this.diskCapacityInBytes = diskCapacityInBytes; + return this; + } + + /** + * Get the file system capacity in bytes. + * + * @return the fileSystemCapacityInBytes value + */ + public Long fileSystemCapacityInBytes() { + return this.fileSystemCapacityInBytes; + } + + /** + * Set the file system capacity in bytes. + * + * @param fileSystemCapacityInBytes the fileSystemCapacityInBytes value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withFileSystemCapacityInBytes(Long fileSystemCapacityInBytes) { + this.fileSystemCapacityInBytes = fileSystemCapacityInBytes; + return this; + } + + /** + * Get the source data transit in MB. + * + * @return the sourceDataInMB value + */ + public Double sourceDataInMB() { + return this.sourceDataInMB; + } + + /** + * Set the source data transit in MB. + * + * @param sourceDataInMB the sourceDataInMB value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withSourceDataInMB(Double sourceDataInMB) { + this.sourceDataInMB = sourceDataInMB; + return this; + } + + /** + * Get the PS data transit in MB. + * + * @return the psDataInMB value + */ + public Double psDataInMB() { + return this.psDataInMB; + } + + /** + * Set the PS data transit in MB. + * + * @param psDataInMB the psDataInMB value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withPsDataInMB(Double psDataInMB) { + this.psDataInMB = psDataInMB; + return this; + } + + /** + * Get the target data transit in MB. + * + * @return the targetDataInMB value + */ + public Double targetDataInMB() { + return this.targetDataInMB; + } + + /** + * Set the target data transit in MB. + * + * @param targetDataInMB the targetDataInMB value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withTargetDataInMB(Double targetDataInMB) { + this.targetDataInMB = targetDataInMB; + return this; + } + + /** + * Get a value indicating whether disk is resized. + * + * @return the diskResized value + */ + public String diskResized() { + return this.diskResized; + } + + /** + * Set a value indicating whether disk is resized. + * + * @param diskResized the diskResized value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withDiskResized(String diskResized) { + this.diskResized = diskResized; + return this; + } + + /** + * Get the last RPO calculated time. + * + * @return the lastRpoCalculatedTime value + */ + public DateTime lastRpoCalculatedTime() { + return this.lastRpoCalculatedTime; + } + + /** + * Set the last RPO calculated time. + * + * @param lastRpoCalculatedTime the lastRpoCalculatedTime value to set + * @return the InMageProtectedDiskDetails object itself. + */ + public InMageProtectedDiskDetails withLastRpoCalculatedTime(DateTime lastRpoCalculatedTime) { + this.lastRpoCalculatedTime = lastRpoCalculatedTime; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageReplicationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageReplicationDetails.java new file mode 100644 index 0000000000000..9cbf438567a2f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageReplicationDetails.java @@ -0,0 +1,992 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMage provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMage") +public class InMageReplicationDetails extends ReplicationProviderSpecificSettings { + /** + * The active location of the VM. If the VM is being protected from Azure, + * this field will take values from { Azure, OnPrem }. If the VM is being + * protected between two data-centers, this field will be OnPrem always. + */ + @JsonProperty(value = "activeSiteType") + private String activeSiteType; + + /** + * The CPU count of the VM on the primary side. + */ + @JsonProperty(value = "sourceVmCpuCount") + private Integer sourceVmCpuCount; + + /** + * The RAM size of the VM on the primary side. + */ + @JsonProperty(value = "sourceVmRamSizeInMB") + private Integer sourceVmRamSizeInMB; + + /** + * The OS details. + */ + @JsonProperty(value = "osDetails") + private OSDiskDetails osDetails; + + /** + * The protection stage. + */ + @JsonProperty(value = "protectionStage") + private String protectionStage; + + /** + * The virtual machine Id. + */ + @JsonProperty(value = "vmId") + private String vmId; + + /** + * The protection state for the vm. + */ + @JsonProperty(value = "vmProtectionState") + private String vmProtectionState; + + /** + * The protection state description for the vm. + */ + @JsonProperty(value = "vmProtectionStateDescription") + private String vmProtectionStateDescription; + + /** + * The resync details of the machine. + */ + @JsonProperty(value = "resyncDetails") + private InitialReplicationDetails resyncDetails; + + /** + * The retention window start time. + */ + @JsonProperty(value = "retentionWindowStart") + private DateTime retentionWindowStart; + + /** + * The retention window end time. + */ + @JsonProperty(value = "retentionWindowEnd") + private DateTime retentionWindowEnd; + + /** + * The compressed data change rate in MB. + */ + @JsonProperty(value = "compressedDataRateInMB") + private Double compressedDataRateInMB; + + /** + * The uncompressed data change rate in MB. + */ + @JsonProperty(value = "uncompressedDataRateInMB") + private Double uncompressedDataRateInMB; + + /** + * The RPO in seconds. + */ + @JsonProperty(value = "rpoInSeconds") + private Long rpoInSeconds; + + /** + * The list of protected disks. + */ + @JsonProperty(value = "protectedDisks") + private List protectedDisks; + + /** + * The source IP address. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The last heartbeat received from the source server. + */ + @JsonProperty(value = "lastHeartbeat") + private DateTime lastHeartbeat; + + /** + * The process server Id. + */ + @JsonProperty(value = "processServerId") + private String processServerId; + + /** + * The master target Id. + */ + @JsonProperty(value = "masterTargetId") + private String masterTargetId; + + /** + * The collection of Consistency points. + */ + @JsonProperty(value = "consistencyPoints") + private Map consistencyPoints; + + /** + * A value indicating whether any disk is resized for this VM. + */ + @JsonProperty(value = "diskResized") + private String diskResized; + + /** + * A value indicating whether the source server requires a restart after + * update. + */ + @JsonProperty(value = "rebootAfterUpdateStatus") + private String rebootAfterUpdateStatus; + + /** + * The multi vm group Id, if any. + */ + @JsonProperty(value = "multiVmGroupId") + private String multiVmGroupId; + + /** + * The multi vm group name, if any. + */ + @JsonProperty(value = "multiVmGroupName") + private String multiVmGroupName; + + /** + * A value indicating whether the multi vm sync is enabled or disabled. + */ + @JsonProperty(value = "multiVmSyncStatus") + private String multiVmSyncStatus; + + /** + * The agent details. + */ + @JsonProperty(value = "agentDetails") + private InMageAgentDetails agentDetails; + + /** + * The vCenter infrastructure Id. + */ + @JsonProperty(value = "vCenterInfrastructureId") + private String vCenterInfrastructureId; + + /** + * The infrastructure VM Id. + */ + @JsonProperty(value = "infrastructureVmId") + private String infrastructureVmId; + + /** + * The PE Network details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * A value indicating the discovery type of the machine. + */ + @JsonProperty(value = "discoveryType") + private String discoveryType; + + /** + * A value indicating the underlying Azure storage account. If the VM is + * not running in Azure, this value shall be set to null. + */ + @JsonProperty(value = "azureStorageAccountId") + private String azureStorageAccountId; + + /** + * The data stores of the on-premise machine Value can be list of strings + * that contain data store names. + */ + @JsonProperty(value = "datastores") + private List datastores; + + /** + * The validation errors of the on-premise machine Value can be list of + * validation errors. + */ + @JsonProperty(value = "validationErrors") + private List validationErrors; + + /** + * The last RPO calculated time. + */ + @JsonProperty(value = "lastRpoCalculatedTime") + private DateTime lastRpoCalculatedTime; + + /** + * The last update time received from on-prem components. + */ + @JsonProperty(value = "lastUpdateReceivedTime") + private DateTime lastUpdateReceivedTime; + + /** + * The replica id of the protected item. + */ + @JsonProperty(value = "replicaId") + private String replicaId; + + /** + * The OS Version of the protected item. + */ + @JsonProperty(value = "osVersion") + private String osVersion; + + /** + * Get the active location of the VM. If the VM is being protected from Azure, this field will take values from { Azure, OnPrem }. If the VM is being protected between two data-centers, this field will be OnPrem always. + * + * @return the activeSiteType value + */ + public String activeSiteType() { + return this.activeSiteType; + } + + /** + * Set the active location of the VM. If the VM is being protected from Azure, this field will take values from { Azure, OnPrem }. If the VM is being protected between two data-centers, this field will be OnPrem always. + * + * @param activeSiteType the activeSiteType value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withActiveSiteType(String activeSiteType) { + this.activeSiteType = activeSiteType; + return this; + } + + /** + * Get the CPU count of the VM on the primary side. + * + * @return the sourceVmCpuCount value + */ + public Integer sourceVmCpuCount() { + return this.sourceVmCpuCount; + } + + /** + * Set the CPU count of the VM on the primary side. + * + * @param sourceVmCpuCount the sourceVmCpuCount value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withSourceVmCpuCount(Integer sourceVmCpuCount) { + this.sourceVmCpuCount = sourceVmCpuCount; + return this; + } + + /** + * Get the RAM size of the VM on the primary side. + * + * @return the sourceVmRamSizeInMB value + */ + public Integer sourceVmRamSizeInMB() { + return this.sourceVmRamSizeInMB; + } + + /** + * Set the RAM size of the VM on the primary side. + * + * @param sourceVmRamSizeInMB the sourceVmRamSizeInMB value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withSourceVmRamSizeInMB(Integer sourceVmRamSizeInMB) { + this.sourceVmRamSizeInMB = sourceVmRamSizeInMB; + return this; + } + + /** + * Get the OS details. + * + * @return the osDetails value + */ + public OSDiskDetails osDetails() { + return this.osDetails; + } + + /** + * Set the OS details. + * + * @param osDetails the osDetails value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withOsDetails(OSDiskDetails osDetails) { + this.osDetails = osDetails; + return this; + } + + /** + * Get the protection stage. + * + * @return the protectionStage value + */ + public String protectionStage() { + return this.protectionStage; + } + + /** + * Set the protection stage. + * + * @param protectionStage the protectionStage value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withProtectionStage(String protectionStage) { + this.protectionStage = protectionStage; + return this; + } + + /** + * Get the virtual machine Id. + * + * @return the vmId value + */ + public String vmId() { + return this.vmId; + } + + /** + * Set the virtual machine Id. + * + * @param vmId the vmId value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withVmId(String vmId) { + this.vmId = vmId; + return this; + } + + /** + * Get the protection state for the vm. + * + * @return the vmProtectionState value + */ + public String vmProtectionState() { + return this.vmProtectionState; + } + + /** + * Set the protection state for the vm. + * + * @param vmProtectionState the vmProtectionState value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withVmProtectionState(String vmProtectionState) { + this.vmProtectionState = vmProtectionState; + return this; + } + + /** + * Get the protection state description for the vm. + * + * @return the vmProtectionStateDescription value + */ + public String vmProtectionStateDescription() { + return this.vmProtectionStateDescription; + } + + /** + * Set the protection state description for the vm. + * + * @param vmProtectionStateDescription the vmProtectionStateDescription value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withVmProtectionStateDescription(String vmProtectionStateDescription) { + this.vmProtectionStateDescription = vmProtectionStateDescription; + return this; + } + + /** + * Get the resync details of the machine. + * + * @return the resyncDetails value + */ + public InitialReplicationDetails resyncDetails() { + return this.resyncDetails; + } + + /** + * Set the resync details of the machine. + * + * @param resyncDetails the resyncDetails value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withResyncDetails(InitialReplicationDetails resyncDetails) { + this.resyncDetails = resyncDetails; + return this; + } + + /** + * Get the retention window start time. + * + * @return the retentionWindowStart value + */ + public DateTime retentionWindowStart() { + return this.retentionWindowStart; + } + + /** + * Set the retention window start time. + * + * @param retentionWindowStart the retentionWindowStart value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withRetentionWindowStart(DateTime retentionWindowStart) { + this.retentionWindowStart = retentionWindowStart; + return this; + } + + /** + * Get the retention window end time. + * + * @return the retentionWindowEnd value + */ + public DateTime retentionWindowEnd() { + return this.retentionWindowEnd; + } + + /** + * Set the retention window end time. + * + * @param retentionWindowEnd the retentionWindowEnd value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withRetentionWindowEnd(DateTime retentionWindowEnd) { + this.retentionWindowEnd = retentionWindowEnd; + return this; + } + + /** + * Get the compressed data change rate in MB. + * + * @return the compressedDataRateInMB value + */ + public Double compressedDataRateInMB() { + return this.compressedDataRateInMB; + } + + /** + * Set the compressed data change rate in MB. + * + * @param compressedDataRateInMB the compressedDataRateInMB value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withCompressedDataRateInMB(Double compressedDataRateInMB) { + this.compressedDataRateInMB = compressedDataRateInMB; + return this; + } + + /** + * Get the uncompressed data change rate in MB. + * + * @return the uncompressedDataRateInMB value + */ + public Double uncompressedDataRateInMB() { + return this.uncompressedDataRateInMB; + } + + /** + * Set the uncompressed data change rate in MB. + * + * @param uncompressedDataRateInMB the uncompressedDataRateInMB value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withUncompressedDataRateInMB(Double uncompressedDataRateInMB) { + this.uncompressedDataRateInMB = uncompressedDataRateInMB; + return this; + } + + /** + * Get the RPO in seconds. + * + * @return the rpoInSeconds value + */ + public Long rpoInSeconds() { + return this.rpoInSeconds; + } + + /** + * Set the RPO in seconds. + * + * @param rpoInSeconds the rpoInSeconds value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withRpoInSeconds(Long rpoInSeconds) { + this.rpoInSeconds = rpoInSeconds; + return this; + } + + /** + * Get the list of protected disks. + * + * @return the protectedDisks value + */ + public List protectedDisks() { + return this.protectedDisks; + } + + /** + * Set the list of protected disks. + * + * @param protectedDisks the protectedDisks value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withProtectedDisks(List protectedDisks) { + this.protectedDisks = protectedDisks; + return this; + } + + /** + * Get the source IP address. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the source IP address. + * + * @param ipAddress the ipAddress value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the last heartbeat received from the source server. + * + * @return the lastHeartbeat value + */ + public DateTime lastHeartbeat() { + return this.lastHeartbeat; + } + + /** + * Set the last heartbeat received from the source server. + * + * @param lastHeartbeat the lastHeartbeat value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withLastHeartbeat(DateTime lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + return this; + } + + /** + * Get the process server Id. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the process server Id. + * + * @param processServerId the processServerId value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the master target Id. + * + * @return the masterTargetId value + */ + public String masterTargetId() { + return this.masterTargetId; + } + + /** + * Set the master target Id. + * + * @param masterTargetId the masterTargetId value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withMasterTargetId(String masterTargetId) { + this.masterTargetId = masterTargetId; + return this; + } + + /** + * Get the collection of Consistency points. + * + * @return the consistencyPoints value + */ + public Map consistencyPoints() { + return this.consistencyPoints; + } + + /** + * Set the collection of Consistency points. + * + * @param consistencyPoints the consistencyPoints value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withConsistencyPoints(Map consistencyPoints) { + this.consistencyPoints = consistencyPoints; + return this; + } + + /** + * Get a value indicating whether any disk is resized for this VM. + * + * @return the diskResized value + */ + public String diskResized() { + return this.diskResized; + } + + /** + * Set a value indicating whether any disk is resized for this VM. + * + * @param diskResized the diskResized value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withDiskResized(String diskResized) { + this.diskResized = diskResized; + return this; + } + + /** + * Get a value indicating whether the source server requires a restart after update. + * + * @return the rebootAfterUpdateStatus value + */ + public String rebootAfterUpdateStatus() { + return this.rebootAfterUpdateStatus; + } + + /** + * Set a value indicating whether the source server requires a restart after update. + * + * @param rebootAfterUpdateStatus the rebootAfterUpdateStatus value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withRebootAfterUpdateStatus(String rebootAfterUpdateStatus) { + this.rebootAfterUpdateStatus = rebootAfterUpdateStatus; + return this; + } + + /** + * Get the multi vm group Id, if any. + * + * @return the multiVmGroupId value + */ + public String multiVmGroupId() { + return this.multiVmGroupId; + } + + /** + * Set the multi vm group Id, if any. + * + * @param multiVmGroupId the multiVmGroupId value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withMultiVmGroupId(String multiVmGroupId) { + this.multiVmGroupId = multiVmGroupId; + return this; + } + + /** + * Get the multi vm group name, if any. + * + * @return the multiVmGroupName value + */ + public String multiVmGroupName() { + return this.multiVmGroupName; + } + + /** + * Set the multi vm group name, if any. + * + * @param multiVmGroupName the multiVmGroupName value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withMultiVmGroupName(String multiVmGroupName) { + this.multiVmGroupName = multiVmGroupName; + return this; + } + + /** + * Get a value indicating whether the multi vm sync is enabled or disabled. + * + * @return the multiVmSyncStatus value + */ + public String multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether the multi vm sync is enabled or disabled. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withMultiVmSyncStatus(String multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + + /** + * Get the agent details. + * + * @return the agentDetails value + */ + public InMageAgentDetails agentDetails() { + return this.agentDetails; + } + + /** + * Set the agent details. + * + * @param agentDetails the agentDetails value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withAgentDetails(InMageAgentDetails agentDetails) { + this.agentDetails = agentDetails; + return this; + } + + /** + * Get the vCenter infrastructure Id. + * + * @return the vCenterInfrastructureId value + */ + public String vCenterInfrastructureId() { + return this.vCenterInfrastructureId; + } + + /** + * Set the vCenter infrastructure Id. + * + * @param vCenterInfrastructureId the vCenterInfrastructureId value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withVCenterInfrastructureId(String vCenterInfrastructureId) { + this.vCenterInfrastructureId = vCenterInfrastructureId; + return this; + } + + /** + * Get the infrastructure VM Id. + * + * @return the infrastructureVmId value + */ + public String infrastructureVmId() { + return this.infrastructureVmId; + } + + /** + * Set the infrastructure VM Id. + * + * @param infrastructureVmId the infrastructureVmId value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withInfrastructureVmId(String infrastructureVmId) { + this.infrastructureVmId = infrastructureVmId; + return this; + } + + /** + * Get the PE Network details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the PE Network details. + * + * @param vmNics the vmNics value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get a value indicating the discovery type of the machine. + * + * @return the discoveryType value + */ + public String discoveryType() { + return this.discoveryType; + } + + /** + * Set a value indicating the discovery type of the machine. + * + * @param discoveryType the discoveryType value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withDiscoveryType(String discoveryType) { + this.discoveryType = discoveryType; + return this; + } + + /** + * Get a value indicating the underlying Azure storage account. If the VM is not running in Azure, this value shall be set to null. + * + * @return the azureStorageAccountId value + */ + public String azureStorageAccountId() { + return this.azureStorageAccountId; + } + + /** + * Set a value indicating the underlying Azure storage account. If the VM is not running in Azure, this value shall be set to null. + * + * @param azureStorageAccountId the azureStorageAccountId value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withAzureStorageAccountId(String azureStorageAccountId) { + this.azureStorageAccountId = azureStorageAccountId; + return this; + } + + /** + * Get the data stores of the on-premise machine Value can be list of strings that contain data store names. + * + * @return the datastores value + */ + public List datastores() { + return this.datastores; + } + + /** + * Set the data stores of the on-premise machine Value can be list of strings that contain data store names. + * + * @param datastores the datastores value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withDatastores(List datastores) { + this.datastores = datastores; + return this; + } + + /** + * Get the validation errors of the on-premise machine Value can be list of validation errors. + * + * @return the validationErrors value + */ + public List validationErrors() { + return this.validationErrors; + } + + /** + * Set the validation errors of the on-premise machine Value can be list of validation errors. + * + * @param validationErrors the validationErrors value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withValidationErrors(List validationErrors) { + this.validationErrors = validationErrors; + return this; + } + + /** + * Get the last RPO calculated time. + * + * @return the lastRpoCalculatedTime value + */ + public DateTime lastRpoCalculatedTime() { + return this.lastRpoCalculatedTime; + } + + /** + * Set the last RPO calculated time. + * + * @param lastRpoCalculatedTime the lastRpoCalculatedTime value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withLastRpoCalculatedTime(DateTime lastRpoCalculatedTime) { + this.lastRpoCalculatedTime = lastRpoCalculatedTime; + return this; + } + + /** + * Get the last update time received from on-prem components. + * + * @return the lastUpdateReceivedTime value + */ + public DateTime lastUpdateReceivedTime() { + return this.lastUpdateReceivedTime; + } + + /** + * Set the last update time received from on-prem components. + * + * @param lastUpdateReceivedTime the lastUpdateReceivedTime value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withLastUpdateReceivedTime(DateTime lastUpdateReceivedTime) { + this.lastUpdateReceivedTime = lastUpdateReceivedTime; + return this; + } + + /** + * Get the replica id of the protected item. + * + * @return the replicaId value + */ + public String replicaId() { + return this.replicaId; + } + + /** + * Set the replica id of the protected item. + * + * @param replicaId the replicaId value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withReplicaId(String replicaId) { + this.replicaId = replicaId; + return this; + } + + /** + * Get the OS Version of the protected item. + * + * @return the osVersion value + */ + public String osVersion() { + return this.osVersion; + } + + /** + * Set the OS Version of the protected item. + * + * @param osVersion the osVersion value to set + * @return the InMageReplicationDetails object itself. + */ + public InMageReplicationDetails withOsVersion(String osVersion) { + this.osVersion = osVersion; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageReprotectInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageReprotectInput.java new file mode 100644 index 0000000000000..817ac731d9edd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageReprotectInput.java @@ -0,0 +1,230 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * InMageAzureV2 specific provider input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMage") +public class InMageReprotectInput extends ReverseReplicationProviderSpecificInput { + /** + * The Master Target Id. + */ + @JsonProperty(value = "masterTargetId", required = true) + private String masterTargetId; + + /** + * The Process Server Id. + */ + @JsonProperty(value = "processServerId", required = true) + private String processServerId; + + /** + * The retention drive to use on the MT. + */ + @JsonProperty(value = "retentionDrive", required = true) + private String retentionDrive; + + /** + * The CS account Id. + */ + @JsonProperty(value = "runAsAccountId") + private String runAsAccountId; + + /** + * The target data store name. + */ + @JsonProperty(value = "datastoreName") + private String datastoreName; + + /** + * The enable disk exclusion input. + */ + @JsonProperty(value = "diskExclusionInput") + private InMageDiskExclusionInput diskExclusionInput; + + /** + * The Policy Id. + */ + @JsonProperty(value = "profileId", required = true) + private String profileId; + + /** + * The disks to include list. + */ + @JsonProperty(value = "disksToInclude") + private List disksToInclude; + + /** + * Get the Master Target Id. + * + * @return the masterTargetId value + */ + public String masterTargetId() { + return this.masterTargetId; + } + + /** + * Set the Master Target Id. + * + * @param masterTargetId the masterTargetId value to set + * @return the InMageReprotectInput object itself. + */ + public InMageReprotectInput withMasterTargetId(String masterTargetId) { + this.masterTargetId = masterTargetId; + return this; + } + + /** + * Get the Process Server Id. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the Process Server Id. + * + * @param processServerId the processServerId value to set + * @return the InMageReprotectInput object itself. + */ + public InMageReprotectInput withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the retention drive to use on the MT. + * + * @return the retentionDrive value + */ + public String retentionDrive() { + return this.retentionDrive; + } + + /** + * Set the retention drive to use on the MT. + * + * @param retentionDrive the retentionDrive value to set + * @return the InMageReprotectInput object itself. + */ + public InMageReprotectInput withRetentionDrive(String retentionDrive) { + this.retentionDrive = retentionDrive; + return this; + } + + /** + * Get the CS account Id. + * + * @return the runAsAccountId value + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Set the CS account Id. + * + * @param runAsAccountId the runAsAccountId value to set + * @return the InMageReprotectInput object itself. + */ + public InMageReprotectInput withRunAsAccountId(String runAsAccountId) { + this.runAsAccountId = runAsAccountId; + return this; + } + + /** + * Get the target data store name. + * + * @return the datastoreName value + */ + public String datastoreName() { + return this.datastoreName; + } + + /** + * Set the target data store name. + * + * @param datastoreName the datastoreName value to set + * @return the InMageReprotectInput object itself. + */ + public InMageReprotectInput withDatastoreName(String datastoreName) { + this.datastoreName = datastoreName; + return this; + } + + /** + * Get the enable disk exclusion input. + * + * @return the diskExclusionInput value + */ + public InMageDiskExclusionInput diskExclusionInput() { + return this.diskExclusionInput; + } + + /** + * Set the enable disk exclusion input. + * + * @param diskExclusionInput the diskExclusionInput value to set + * @return the InMageReprotectInput object itself. + */ + public InMageReprotectInput withDiskExclusionInput(InMageDiskExclusionInput diskExclusionInput) { + this.diskExclusionInput = diskExclusionInput; + return this; + } + + /** + * Get the Policy Id. + * + * @return the profileId value + */ + public String profileId() { + return this.profileId; + } + + /** + * Set the Policy Id. + * + * @param profileId the profileId value to set + * @return the InMageReprotectInput object itself. + */ + public InMageReprotectInput withProfileId(String profileId) { + this.profileId = profileId; + return this; + } + + /** + * Get the disks to include list. + * + * @return the disksToInclude value + */ + public List disksToInclude() { + return this.disksToInclude; + } + + /** + * Set the disks to include list. + * + * @param disksToInclude the disksToInclude value to set + * @return the InMageReprotectInput object itself. + */ + public InMageReprotectInput withDisksToInclude(List disksToInclude) { + this.disksToInclude = disksToInclude; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageV2RpRecoveryPointType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageV2RpRecoveryPointType.java new file mode 100644 index 0000000000000..421eae03a0586 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageV2RpRecoveryPointType.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for InMageV2RpRecoveryPointType. + */ +public final class InMageV2RpRecoveryPointType extends ExpandableStringEnum { + /** Static value Latest for InMageV2RpRecoveryPointType. */ + public static final InMageV2RpRecoveryPointType LATEST = fromString("Latest"); + + /** Static value LatestApplicationConsistent for InMageV2RpRecoveryPointType. */ + public static final InMageV2RpRecoveryPointType LATEST_APPLICATION_CONSISTENT = fromString("LatestApplicationConsistent"); + + /** Static value LatestCrashConsistent for InMageV2RpRecoveryPointType. */ + public static final InMageV2RpRecoveryPointType LATEST_CRASH_CONSISTENT = fromString("LatestCrashConsistent"); + + /** Static value LatestProcessed for InMageV2RpRecoveryPointType. */ + public static final InMageV2RpRecoveryPointType LATEST_PROCESSED = fromString("LatestProcessed"); + + /** + * Creates or finds a InMageV2RpRecoveryPointType from its string representation. + * @param name a name to look for + * @return the corresponding InMageV2RpRecoveryPointType + */ + @JsonCreator + public static InMageV2RpRecoveryPointType fromString(String name) { + return fromString(name, InMageV2RpRecoveryPointType.class); + } + + /** + * @return known InMageV2RpRecoveryPointType values + */ + public static Collection values() { + return values(InMageV2RpRecoveryPointType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageVolumeExclusionOptions.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageVolumeExclusionOptions.java new file mode 100644 index 0000000000000..aa55f067b4d02 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InMageVolumeExclusionOptions.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Guest disk signature based disk exclusion option when doing enable + * protection of virtual machine in InMage provider. + */ +public class InMageVolumeExclusionOptions { + /** + * The volume label. The disk having any volume with this label will be + * excluded from replication. + */ + @JsonProperty(value = "volumeLabel") + private String volumeLabel; + + /** + * The value indicating whether to exclude multi volume disk or not. If a + * disk has multiple volumes and one of the volume has label matching with + * VolumeLabel this disk will be excluded from replication if + * OnlyExcludeIfSingleVolume is false. + */ + @JsonProperty(value = "onlyExcludeIfSingleVolume") + private String onlyExcludeIfSingleVolume; + + /** + * Get the volume label. The disk having any volume with this label will be excluded from replication. + * + * @return the volumeLabel value + */ + public String volumeLabel() { + return this.volumeLabel; + } + + /** + * Set the volume label. The disk having any volume with this label will be excluded from replication. + * + * @param volumeLabel the volumeLabel value to set + * @return the InMageVolumeExclusionOptions object itself. + */ + public InMageVolumeExclusionOptions withVolumeLabel(String volumeLabel) { + this.volumeLabel = volumeLabel; + return this; + } + + /** + * Get the value indicating whether to exclude multi volume disk or not. If a disk has multiple volumes and one of the volume has label matching with VolumeLabel this disk will be excluded from replication if OnlyExcludeIfSingleVolume is false. + * + * @return the onlyExcludeIfSingleVolume value + */ + public String onlyExcludeIfSingleVolume() { + return this.onlyExcludeIfSingleVolume; + } + + /** + * Set the value indicating whether to exclude multi volume disk or not. If a disk has multiple volumes and one of the volume has label matching with VolumeLabel this disk will be excluded from replication if OnlyExcludeIfSingleVolume is false. + * + * @param onlyExcludeIfSingleVolume the onlyExcludeIfSingleVolume value to set + * @return the InMageVolumeExclusionOptions object itself. + */ + public InMageVolumeExclusionOptions withOnlyExcludeIfSingleVolume(String onlyExcludeIfSingleVolume) { + this.onlyExcludeIfSingleVolume = onlyExcludeIfSingleVolume; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InconsistentVmDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InconsistentVmDetails.java new file mode 100644 index 0000000000000..fdd156ec51527 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InconsistentVmDetails.java @@ -0,0 +1,124 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class stores the monitoring details for consistency check of + * inconsistent Protected Entity. + */ +public class InconsistentVmDetails { + /** + * The Vm name. + */ + @JsonProperty(value = "vmName") + private String vmName; + + /** + * The Cloud name. + */ + @JsonProperty(value = "cloudName") + private String cloudName; + + /** + * The list of details regarding state of the Protected Entity in SRS and + * On prem. + */ + @JsonProperty(value = "details") + private List details; + + /** + * The list of error ids. + */ + @JsonProperty(value = "errorIds") + private List errorIds; + + /** + * Get the Vm name. + * + * @return the vmName value + */ + public String vmName() { + return this.vmName; + } + + /** + * Set the Vm name. + * + * @param vmName the vmName value to set + * @return the InconsistentVmDetails object itself. + */ + public InconsistentVmDetails withVmName(String vmName) { + this.vmName = vmName; + return this; + } + + /** + * Get the Cloud name. + * + * @return the cloudName value + */ + public String cloudName() { + return this.cloudName; + } + + /** + * Set the Cloud name. + * + * @param cloudName the cloudName value to set + * @return the InconsistentVmDetails object itself. + */ + public InconsistentVmDetails withCloudName(String cloudName) { + this.cloudName = cloudName; + return this; + } + + /** + * Get the list of details regarding state of the Protected Entity in SRS and On prem. + * + * @return the details value + */ + public List details() { + return this.details; + } + + /** + * Set the list of details regarding state of the Protected Entity in SRS and On prem. + * + * @param details the details value to set + * @return the InconsistentVmDetails object itself. + */ + public InconsistentVmDetails withDetails(List details) { + this.details = details; + return this; + } + + /** + * Get the list of error ids. + * + * @return the errorIds value + */ + public List errorIds() { + return this.errorIds; + } + + /** + * Set the list of error ids. + * + * @param errorIds the errorIds value to set + * @return the InconsistentVmDetails object itself. + */ + public InconsistentVmDetails withErrorIds(List errorIds) { + this.errorIds = errorIds; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InitialReplicationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InitialReplicationDetails.java new file mode 100644 index 0000000000000..bd5e425b8fceb --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InitialReplicationDetails.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Initial replication details. + */ +public class InitialReplicationDetails { + /** + * Initial replication type. + */ + @JsonProperty(value = "initialReplicationType") + private String initialReplicationType; + + /** + * The initial replication progress percentage. + */ + @JsonProperty(value = "initialReplicationProgressPercentage") + private String initialReplicationProgressPercentage; + + /** + * Get initial replication type. + * + * @return the initialReplicationType value + */ + public String initialReplicationType() { + return this.initialReplicationType; + } + + /** + * Set initial replication type. + * + * @param initialReplicationType the initialReplicationType value to set + * @return the InitialReplicationDetails object itself. + */ + public InitialReplicationDetails withInitialReplicationType(String initialReplicationType) { + this.initialReplicationType = initialReplicationType; + return this; + } + + /** + * Get the initial replication progress percentage. + * + * @return the initialReplicationProgressPercentage value + */ + public String initialReplicationProgressPercentage() { + return this.initialReplicationProgressPercentage; + } + + /** + * Set the initial replication progress percentage. + * + * @param initialReplicationProgressPercentage the initialReplicationProgressPercentage value to set + * @return the InitialReplicationDetails object itself. + */ + public InitialReplicationDetails withInitialReplicationProgressPercentage(String initialReplicationProgressPercentage) { + this.initialReplicationProgressPercentage = initialReplicationProgressPercentage; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InlineWorkflowTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InlineWorkflowTaskDetails.java new file mode 100644 index 0000000000000..a545c79086885 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InlineWorkflowTaskDetails.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the inline workflow task details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InlineWorkflowTaskDetails") +public class InlineWorkflowTaskDetails extends GroupTaskDetails { + /** + * The list of child workflow ids. + */ + @JsonProperty(value = "workflowIds") + private List workflowIds; + + /** + * Get the list of child workflow ids. + * + * @return the workflowIds value + */ + public List workflowIds() { + return this.workflowIds; + } + + /** + * Set the list of child workflow ids. + * + * @param workflowIds the workflowIds value to set + * @return the InlineWorkflowTaskDetails object itself. + */ + public InlineWorkflowTaskDetails withWorkflowIds(List workflowIds) { + this.workflowIds = workflowIds; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InnerHealthError.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InnerHealthError.java new file mode 100644 index 0000000000000..02a084b2e304a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InnerHealthError.java @@ -0,0 +1,335 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Implements InnerHealthError class. HealthError object has a list of + * InnerHealthErrors as child errors. InnerHealthError is used because this + * will prevent an infinite loop of structures when Hydra tries to + * auto-generate the contract. We are exposing the related health errors as + * inner health errors and all API consumers can utilize this in the same + * fashion as Exception -&gt; InnerException. + */ +public class InnerHealthError { + /** + * Source of error. + */ + @JsonProperty(value = "errorSource") + private String errorSource; + + /** + * Type of error. + */ + @JsonProperty(value = "errorType") + private String errorType; + + /** + * Level of error. + */ + @JsonProperty(value = "errorLevel") + private String errorLevel; + + /** + * Category of error. + */ + @JsonProperty(value = "errorCategory") + private String errorCategory; + + /** + * Error code. + */ + @JsonProperty(value = "errorCode") + private String errorCode; + + /** + * Summary message of the entity. + */ + @JsonProperty(value = "summaryMessage") + private String summaryMessage; + + /** + * Error message. + */ + @JsonProperty(value = "errorMessage") + private String errorMessage; + + /** + * Possible causes of error. + */ + @JsonProperty(value = "possibleCauses") + private String possibleCauses; + + /** + * Recommended action to resolve error. + */ + @JsonProperty(value = "recommendedAction") + private String recommendedAction; + + /** + * Error creation time (UTC). + */ + @JsonProperty(value = "creationTimeUtc") + private DateTime creationTimeUtc; + + /** + * DRA error message. + */ + @JsonProperty(value = "recoveryProviderErrorMessage") + private String recoveryProviderErrorMessage; + + /** + * ID of the entity. + */ + @JsonProperty(value = "entityId") + private String entityId; + + /** + * Get source of error. + * + * @return the errorSource value + */ + public String errorSource() { + return this.errorSource; + } + + /** + * Set source of error. + * + * @param errorSource the errorSource value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withErrorSource(String errorSource) { + this.errorSource = errorSource; + return this; + } + + /** + * Get type of error. + * + * @return the errorType value + */ + public String errorType() { + return this.errorType; + } + + /** + * Set type of error. + * + * @param errorType the errorType value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withErrorType(String errorType) { + this.errorType = errorType; + return this; + } + + /** + * Get level of error. + * + * @return the errorLevel value + */ + public String errorLevel() { + return this.errorLevel; + } + + /** + * Set level of error. + * + * @param errorLevel the errorLevel value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withErrorLevel(String errorLevel) { + this.errorLevel = errorLevel; + return this; + } + + /** + * Get category of error. + * + * @return the errorCategory value + */ + public String errorCategory() { + return this.errorCategory; + } + + /** + * Set category of error. + * + * @param errorCategory the errorCategory value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withErrorCategory(String errorCategory) { + this.errorCategory = errorCategory; + return this; + } + + /** + * Get error code. + * + * @return the errorCode value + */ + public String errorCode() { + return this.errorCode; + } + + /** + * Set error code. + * + * @param errorCode the errorCode value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withErrorCode(String errorCode) { + this.errorCode = errorCode; + return this; + } + + /** + * Get summary message of the entity. + * + * @return the summaryMessage value + */ + public String summaryMessage() { + return this.summaryMessage; + } + + /** + * Set summary message of the entity. + * + * @param summaryMessage the summaryMessage value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withSummaryMessage(String summaryMessage) { + this.summaryMessage = summaryMessage; + return this; + } + + /** + * Get error message. + * + * @return the errorMessage value + */ + public String errorMessage() { + return this.errorMessage; + } + + /** + * Set error message. + * + * @param errorMessage the errorMessage value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + /** + * Get possible causes of error. + * + * @return the possibleCauses value + */ + public String possibleCauses() { + return this.possibleCauses; + } + + /** + * Set possible causes of error. + * + * @param possibleCauses the possibleCauses value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withPossibleCauses(String possibleCauses) { + this.possibleCauses = possibleCauses; + return this; + } + + /** + * Get recommended action to resolve error. + * + * @return the recommendedAction value + */ + public String recommendedAction() { + return this.recommendedAction; + } + + /** + * Set recommended action to resolve error. + * + * @param recommendedAction the recommendedAction value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withRecommendedAction(String recommendedAction) { + this.recommendedAction = recommendedAction; + return this; + } + + /** + * Get error creation time (UTC). + * + * @return the creationTimeUtc value + */ + public DateTime creationTimeUtc() { + return this.creationTimeUtc; + } + + /** + * Set error creation time (UTC). + * + * @param creationTimeUtc the creationTimeUtc value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withCreationTimeUtc(DateTime creationTimeUtc) { + this.creationTimeUtc = creationTimeUtc; + return this; + } + + /** + * Get dRA error message. + * + * @return the recoveryProviderErrorMessage value + */ + public String recoveryProviderErrorMessage() { + return this.recoveryProviderErrorMessage; + } + + /** + * Set dRA error message. + * + * @param recoveryProviderErrorMessage the recoveryProviderErrorMessage value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withRecoveryProviderErrorMessage(String recoveryProviderErrorMessage) { + this.recoveryProviderErrorMessage = recoveryProviderErrorMessage; + return this; + } + + /** + * Get iD of the entity. + * + * @return the entityId value + */ + public String entityId() { + return this.entityId; + } + + /** + * Set iD of the entity. + * + * @param entityId the entityId value to set + * @return the InnerHealthError object itself. + */ + public InnerHealthError withEntityId(String entityId) { + this.entityId = entityId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InputEndpoint.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InputEndpoint.java new file mode 100644 index 0000000000000..bf6d7dbb4e11c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/InputEndpoint.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Azure VM input endpoint details. + */ +public class InputEndpoint { + /** + * The input endpoint name. + */ + @JsonProperty(value = "endpointName") + private String endpointName; + + /** + * The input endpoint private port. + */ + @JsonProperty(value = "privatePort") + private Integer privatePort; + + /** + * The input endpoint public port. + */ + @JsonProperty(value = "publicPort") + private Integer publicPort; + + /** + * The input endpoint protocol. + */ + @JsonProperty(value = "protocol") + private String protocol; + + /** + * Get the input endpoint name. + * + * @return the endpointName value + */ + public String endpointName() { + return this.endpointName; + } + + /** + * Set the input endpoint name. + * + * @param endpointName the endpointName value to set + * @return the InputEndpoint object itself. + */ + public InputEndpoint withEndpointName(String endpointName) { + this.endpointName = endpointName; + return this; + } + + /** + * Get the input endpoint private port. + * + * @return the privatePort value + */ + public Integer privatePort() { + return this.privatePort; + } + + /** + * Set the input endpoint private port. + * + * @param privatePort the privatePort value to set + * @return the InputEndpoint object itself. + */ + public InputEndpoint withPrivatePort(Integer privatePort) { + this.privatePort = privatePort; + return this; + } + + /** + * Get the input endpoint public port. + * + * @return the publicPort value + */ + public Integer publicPort() { + return this.publicPort; + } + + /** + * Set the input endpoint public port. + * + * @param publicPort the publicPort value to set + * @return the InputEndpoint object itself. + */ + public InputEndpoint withPublicPort(Integer publicPort) { + this.publicPort = publicPort; + return this; + } + + /** + * Get the input endpoint protocol. + * + * @return the protocol value + */ + public String protocol() { + return this.protocol; + } + + /** + * Set the input endpoint protocol. + * + * @param protocol the protocol value to set + * @return the InputEndpoint object itself. + */ + public InputEndpoint withProtocol(String protocol) { + this.protocol = protocol; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Job.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Job.java new file mode 100644 index 0000000000000..b10f3fa303e57 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Job.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.JobInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing Job. + */ +public interface Job extends HasInner, Indexable, Refreshable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + JobProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobDetails.java new file mode 100644 index 0000000000000..5ccc406da30e6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobDetails.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Job details based on specific job type. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("JobDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "AsrJobDetails", value = AsrJobDetails.class), + @JsonSubTypes.Type(name = "ExportJobDetails", value = ExportJobDetails.class), + @JsonSubTypes.Type(name = "FailoverJobDetails", value = FailoverJobDetails.class), + @JsonSubTypes.Type(name = "SwitchProtectionJobDetails", value = SwitchProtectionJobDetails.class), + @JsonSubTypes.Type(name = "TestFailoverJobDetails", value = TestFailoverJobDetails.class) +}) +public class JobDetails { + /** + * The affected object properties like source server, source cloud, target + * server, target cloud etc. based on the workflow object details. + */ + @JsonProperty(value = "affectedObjectDetails") + private Map affectedObjectDetails; + + /** + * Get the affected object properties like source server, source cloud, target server, target cloud etc. based on the workflow object details. + * + * @return the affectedObjectDetails value + */ + public Map affectedObjectDetails() { + return this.affectedObjectDetails; + } + + /** + * Set the affected object properties like source server, source cloud, target server, target cloud etc. based on the workflow object details. + * + * @param affectedObjectDetails the affectedObjectDetails value to set + * @return the JobDetails object itself. + */ + public JobDetails withAffectedObjectDetails(Map affectedObjectDetails) { + this.affectedObjectDetails = affectedObjectDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobEntity.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobEntity.java new file mode 100644 index 0000000000000..1074b9f5614c0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobEntity.java @@ -0,0 +1,174 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class contains the minimal job details required to navigate to the + * desired drill down. + */ +public class JobEntity { + /** + * The job id. + */ + @JsonProperty(value = "jobId") + private String jobId; + + /** + * The job display name. + */ + @JsonProperty(value = "jobFriendlyName") + private String jobFriendlyName; + + /** + * The object id. + */ + @JsonProperty(value = "targetObjectId") + private String targetObjectId; + + /** + * The object name. + */ + @JsonProperty(value = "targetObjectName") + private String targetObjectName; + + /** + * The workflow affected object type. + */ + @JsonProperty(value = "targetInstanceType") + private String targetInstanceType; + + /** + * The job name. Enum type ScenarioName. + */ + @JsonProperty(value = "jobScenarioName") + private String jobScenarioName; + + /** + * Get the job id. + * + * @return the jobId value + */ + public String jobId() { + return this.jobId; + } + + /** + * Set the job id. + * + * @param jobId the jobId value to set + * @return the JobEntity object itself. + */ + public JobEntity withJobId(String jobId) { + this.jobId = jobId; + return this; + } + + /** + * Get the job display name. + * + * @return the jobFriendlyName value + */ + public String jobFriendlyName() { + return this.jobFriendlyName; + } + + /** + * Set the job display name. + * + * @param jobFriendlyName the jobFriendlyName value to set + * @return the JobEntity object itself. + */ + public JobEntity withJobFriendlyName(String jobFriendlyName) { + this.jobFriendlyName = jobFriendlyName; + return this; + } + + /** + * Get the object id. + * + * @return the targetObjectId value + */ + public String targetObjectId() { + return this.targetObjectId; + } + + /** + * Set the object id. + * + * @param targetObjectId the targetObjectId value to set + * @return the JobEntity object itself. + */ + public JobEntity withTargetObjectId(String targetObjectId) { + this.targetObjectId = targetObjectId; + return this; + } + + /** + * Get the object name. + * + * @return the targetObjectName value + */ + public String targetObjectName() { + return this.targetObjectName; + } + + /** + * Set the object name. + * + * @param targetObjectName the targetObjectName value to set + * @return the JobEntity object itself. + */ + public JobEntity withTargetObjectName(String targetObjectName) { + this.targetObjectName = targetObjectName; + return this; + } + + /** + * Get the workflow affected object type. + * + * @return the targetInstanceType value + */ + public String targetInstanceType() { + return this.targetInstanceType; + } + + /** + * Set the workflow affected object type. + * + * @param targetInstanceType the targetInstanceType value to set + * @return the JobEntity object itself. + */ + public JobEntity withTargetInstanceType(String targetInstanceType) { + this.targetInstanceType = targetInstanceType; + return this; + } + + /** + * Get the job name. Enum type ScenarioName. + * + * @return the jobScenarioName value + */ + public String jobScenarioName() { + return this.jobScenarioName; + } + + /** + * Set the job name. Enum type ScenarioName. + * + * @param jobScenarioName the jobScenarioName value to set + * @return the JobEntity object itself. + */ + public JobEntity withJobScenarioName(String jobScenarioName) { + this.jobScenarioName = jobScenarioName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobErrorDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobErrorDetails.java new file mode 100644 index 0000000000000..4588cf7f6beea --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobErrorDetails.java @@ -0,0 +1,148 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class contains the error details per object. + */ +public class JobErrorDetails { + /** + * The Service error details. + */ + @JsonProperty(value = "serviceErrorDetails") + private ServiceError serviceErrorDetails; + + /** + * The Provider error details. + */ + @JsonProperty(value = "providerErrorDetails") + private ProviderError providerErrorDetails; + + /** + * Error level of error. + */ + @JsonProperty(value = "errorLevel") + private String errorLevel; + + /** + * The creation time of job error. + */ + @JsonProperty(value = "creationTime") + private DateTime creationTime; + + /** + * The Id of the task. + */ + @JsonProperty(value = "taskId") + private String taskId; + + /** + * Get the Service error details. + * + * @return the serviceErrorDetails value + */ + public ServiceError serviceErrorDetails() { + return this.serviceErrorDetails; + } + + /** + * Set the Service error details. + * + * @param serviceErrorDetails the serviceErrorDetails value to set + * @return the JobErrorDetails object itself. + */ + public JobErrorDetails withServiceErrorDetails(ServiceError serviceErrorDetails) { + this.serviceErrorDetails = serviceErrorDetails; + return this; + } + + /** + * Get the Provider error details. + * + * @return the providerErrorDetails value + */ + public ProviderError providerErrorDetails() { + return this.providerErrorDetails; + } + + /** + * Set the Provider error details. + * + * @param providerErrorDetails the providerErrorDetails value to set + * @return the JobErrorDetails object itself. + */ + public JobErrorDetails withProviderErrorDetails(ProviderError providerErrorDetails) { + this.providerErrorDetails = providerErrorDetails; + return this; + } + + /** + * Get error level of error. + * + * @return the errorLevel value + */ + public String errorLevel() { + return this.errorLevel; + } + + /** + * Set error level of error. + * + * @param errorLevel the errorLevel value to set + * @return the JobErrorDetails object itself. + */ + public JobErrorDetails withErrorLevel(String errorLevel) { + this.errorLevel = errorLevel; + return this; + } + + /** + * Get the creation time of job error. + * + * @return the creationTime value + */ + public DateTime creationTime() { + return this.creationTime; + } + + /** + * Set the creation time of job error. + * + * @param creationTime the creationTime value to set + * @return the JobErrorDetails object itself. + */ + public JobErrorDetails withCreationTime(DateTime creationTime) { + this.creationTime = creationTime; + return this; + } + + /** + * Get the Id of the task. + * + * @return the taskId value + */ + public String taskId() { + return this.taskId; + } + + /** + * Set the Id of the task. + * + * @param taskId the taskId value to set + * @return the JobErrorDetails object itself. + */ + public JobErrorDetails withTaskId(String taskId) { + this.taskId = taskId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobProperties.java new file mode 100644 index 0000000000000..a73fe2a1ecc32 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobProperties.java @@ -0,0 +1,387 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Job custom data details. + */ +public class JobProperties { + /** + * The activity id. + */ + @JsonProperty(value = "activityId") + private String activityId; + + /** + * The ScenarioName. + */ + @JsonProperty(value = "scenarioName") + private String scenarioName; + + /** + * The DisplayName. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The status of the Job. It is one of these values - NotStarted, + * InProgress, Succeeded, Failed, Cancelled, Suspended or Other. + */ + @JsonProperty(value = "state") + private String state; + + /** + * The description of the state of the Job. For e.g. - For Succeeded state, + * description can be Completed, PartiallySucceeded, + * CompletedWithInformation or Skipped. + */ + @JsonProperty(value = "stateDescription") + private String stateDescription; + + /** + * The tasks. + */ + @JsonProperty(value = "tasks") + private List tasks; + + /** + * The errors. + */ + @JsonProperty(value = "errors") + private List errors; + + /** + * The start time. + */ + @JsonProperty(value = "startTime") + private DateTime startTime; + + /** + * The end time. + */ + @JsonProperty(value = "endTime") + private DateTime endTime; + + /** + * The Allowed action the job. + */ + @JsonProperty(value = "allowedActions") + private List allowedActions; + + /** + * The affected Object Id. + */ + @JsonProperty(value = "targetObjectId") + private String targetObjectId; + + /** + * The name of the affected object. + */ + @JsonProperty(value = "targetObjectName") + private String targetObjectName; + + /** + * The type of the affected object which is of + * {Microsoft.Azure.SiteRecovery.V2015_11_10.AffectedObjectType} class. + */ + @JsonProperty(value = "targetInstanceType") + private String targetInstanceType; + + /** + * The custom job details like test failover job details. + */ + @JsonProperty(value = "customDetails") + private JobDetails customDetails; + + /** + * Get the activity id. + * + * @return the activityId value + */ + public String activityId() { + return this.activityId; + } + + /** + * Set the activity id. + * + * @param activityId the activityId value to set + * @return the JobProperties object itself. + */ + public JobProperties withActivityId(String activityId) { + this.activityId = activityId; + return this; + } + + /** + * Get the ScenarioName. + * + * @return the scenarioName value + */ + public String scenarioName() { + return this.scenarioName; + } + + /** + * Set the ScenarioName. + * + * @param scenarioName the scenarioName value to set + * @return the JobProperties object itself. + */ + public JobProperties withScenarioName(String scenarioName) { + this.scenarioName = scenarioName; + return this; + } + + /** + * Get the DisplayName. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the DisplayName. + * + * @param friendlyName the friendlyName value to set + * @return the JobProperties object itself. + */ + public JobProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the status of the Job. It is one of these values - NotStarted, InProgress, Succeeded, Failed, Cancelled, Suspended or Other. + * + * @return the state value + */ + public String state() { + return this.state; + } + + /** + * Set the status of the Job. It is one of these values - NotStarted, InProgress, Succeeded, Failed, Cancelled, Suspended or Other. + * + * @param state the state value to set + * @return the JobProperties object itself. + */ + public JobProperties withState(String state) { + this.state = state; + return this; + } + + /** + * Get the description of the state of the Job. For e.g. - For Succeeded state, description can be Completed, PartiallySucceeded, CompletedWithInformation or Skipped. + * + * @return the stateDescription value + */ + public String stateDescription() { + return this.stateDescription; + } + + /** + * Set the description of the state of the Job. For e.g. - For Succeeded state, description can be Completed, PartiallySucceeded, CompletedWithInformation or Skipped. + * + * @param stateDescription the stateDescription value to set + * @return the JobProperties object itself. + */ + public JobProperties withStateDescription(String stateDescription) { + this.stateDescription = stateDescription; + return this; + } + + /** + * Get the tasks. + * + * @return the tasks value + */ + public List tasks() { + return this.tasks; + } + + /** + * Set the tasks. + * + * @param tasks the tasks value to set + * @return the JobProperties object itself. + */ + public JobProperties withTasks(List tasks) { + this.tasks = tasks; + return this; + } + + /** + * Get the errors. + * + * @return the errors value + */ + public List errors() { + return this.errors; + } + + /** + * Set the errors. + * + * @param errors the errors value to set + * @return the JobProperties object itself. + */ + public JobProperties withErrors(List errors) { + this.errors = errors; + return this; + } + + /** + * Get the start time. + * + * @return the startTime value + */ + public DateTime startTime() { + return this.startTime; + } + + /** + * Set the start time. + * + * @param startTime the startTime value to set + * @return the JobProperties object itself. + */ + public JobProperties withStartTime(DateTime startTime) { + this.startTime = startTime; + return this; + } + + /** + * Get the end time. + * + * @return the endTime value + */ + public DateTime endTime() { + return this.endTime; + } + + /** + * Set the end time. + * + * @param endTime the endTime value to set + * @return the JobProperties object itself. + */ + public JobProperties withEndTime(DateTime endTime) { + this.endTime = endTime; + return this; + } + + /** + * Get the Allowed action the job. + * + * @return the allowedActions value + */ + public List allowedActions() { + return this.allowedActions; + } + + /** + * Set the Allowed action the job. + * + * @param allowedActions the allowedActions value to set + * @return the JobProperties object itself. + */ + public JobProperties withAllowedActions(List allowedActions) { + this.allowedActions = allowedActions; + return this; + } + + /** + * Get the affected Object Id. + * + * @return the targetObjectId value + */ + public String targetObjectId() { + return this.targetObjectId; + } + + /** + * Set the affected Object Id. + * + * @param targetObjectId the targetObjectId value to set + * @return the JobProperties object itself. + */ + public JobProperties withTargetObjectId(String targetObjectId) { + this.targetObjectId = targetObjectId; + return this; + } + + /** + * Get the name of the affected object. + * + * @return the targetObjectName value + */ + public String targetObjectName() { + return this.targetObjectName; + } + + /** + * Set the name of the affected object. + * + * @param targetObjectName the targetObjectName value to set + * @return the JobProperties object itself. + */ + public JobProperties withTargetObjectName(String targetObjectName) { + this.targetObjectName = targetObjectName; + return this; + } + + /** + * Get the type of the affected object which is of {Microsoft.Azure.SiteRecovery.V2015_11_10.AffectedObjectType} class. + * + * @return the targetInstanceType value + */ + public String targetInstanceType() { + return this.targetInstanceType; + } + + /** + * Set the type of the affected object which is of {Microsoft.Azure.SiteRecovery.V2015_11_10.AffectedObjectType} class. + * + * @param targetInstanceType the targetInstanceType value to set + * @return the JobProperties object itself. + */ + public JobProperties withTargetInstanceType(String targetInstanceType) { + this.targetInstanceType = targetInstanceType; + return this; + } + + /** + * Get the custom job details like test failover job details. + * + * @return the customDetails value + */ + public JobDetails customDetails() { + return this.customDetails; + } + + /** + * Set the custom job details like test failover job details. + * + * @param customDetails the customDetails value to set + * @return the JobProperties object itself. + */ + public JobProperties withCustomDetails(JobDetails customDetails) { + this.customDetails = customDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobQueryParameter.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobQueryParameter.java new file mode 100644 index 0000000000000..062b9fbac86fb --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobQueryParameter.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Query parameter to enumerate jobs. + */ +public class JobQueryParameter { + /** + * Date time to get jobs from. + */ + @JsonProperty(value = "startTime") + private String startTime; + + /** + * Date time to get jobs up to. + */ + @JsonProperty(value = "endTime") + private String endTime; + + /** + * The Id of the fabric to search jobs under. + */ + @JsonProperty(value = "fabricId") + private String fabricId; + + /** + * The type of objects. + */ + @JsonProperty(value = "affectedObjectTypes") + private String affectedObjectTypes; + + /** + * The states of the job to be filtered can be in. + */ + @JsonProperty(value = "jobStatus") + private String jobStatus; + + /** + * Get date time to get jobs from. + * + * @return the startTime value + */ + public String startTime() { + return this.startTime; + } + + /** + * Set date time to get jobs from. + * + * @param startTime the startTime value to set + * @return the JobQueryParameter object itself. + */ + public JobQueryParameter withStartTime(String startTime) { + this.startTime = startTime; + return this; + } + + /** + * Get date time to get jobs up to. + * + * @return the endTime value + */ + public String endTime() { + return this.endTime; + } + + /** + * Set date time to get jobs up to. + * + * @param endTime the endTime value to set + * @return the JobQueryParameter object itself. + */ + public JobQueryParameter withEndTime(String endTime) { + this.endTime = endTime; + return this; + } + + /** + * Get the Id of the fabric to search jobs under. + * + * @return the fabricId value + */ + public String fabricId() { + return this.fabricId; + } + + /** + * Set the Id of the fabric to search jobs under. + * + * @param fabricId the fabricId value to set + * @return the JobQueryParameter object itself. + */ + public JobQueryParameter withFabricId(String fabricId) { + this.fabricId = fabricId; + return this; + } + + /** + * Get the type of objects. + * + * @return the affectedObjectTypes value + */ + public String affectedObjectTypes() { + return this.affectedObjectTypes; + } + + /** + * Set the type of objects. + * + * @param affectedObjectTypes the affectedObjectTypes value to set + * @return the JobQueryParameter object itself. + */ + public JobQueryParameter withAffectedObjectTypes(String affectedObjectTypes) { + this.affectedObjectTypes = affectedObjectTypes; + return this; + } + + /** + * Get the states of the job to be filtered can be in. + * + * @return the jobStatus value + */ + public String jobStatus() { + return this.jobStatus; + } + + /** + * Set the states of the job to be filtered can be in. + * + * @param jobStatus the jobStatus value to set + * @return the JobQueryParameter object itself. + */ + public JobQueryParameter withJobStatus(String jobStatus) { + this.jobStatus = jobStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobStatusEventDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobStatusEventDetails.java new file mode 100644 index 0000000000000..e84009188f68a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobStatusEventDetails.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Model class for event details of a job status event. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("JobStatus") +public class JobStatusEventDetails extends EventSpecificDetails { + /** + * Job arm id for the event. + */ + @JsonProperty(value = "jobId") + private String jobId; + + /** + * JobName for the Event. + */ + @JsonProperty(value = "jobFriendlyName") + private String jobFriendlyName; + + /** + * JobStatus for the Event. + */ + @JsonProperty(value = "jobStatus") + private String jobStatus; + + /** + * AffectedObjectType for the event. + */ + @JsonProperty(value = "affectedObjectType") + private String affectedObjectType; + + /** + * Get job arm id for the event. + * + * @return the jobId value + */ + public String jobId() { + return this.jobId; + } + + /** + * Set job arm id for the event. + * + * @param jobId the jobId value to set + * @return the JobStatusEventDetails object itself. + */ + public JobStatusEventDetails withJobId(String jobId) { + this.jobId = jobId; + return this; + } + + /** + * Get jobName for the Event. + * + * @return the jobFriendlyName value + */ + public String jobFriendlyName() { + return this.jobFriendlyName; + } + + /** + * Set jobName for the Event. + * + * @param jobFriendlyName the jobFriendlyName value to set + * @return the JobStatusEventDetails object itself. + */ + public JobStatusEventDetails withJobFriendlyName(String jobFriendlyName) { + this.jobFriendlyName = jobFriendlyName; + return this; + } + + /** + * Get jobStatus for the Event. + * + * @return the jobStatus value + */ + public String jobStatus() { + return this.jobStatus; + } + + /** + * Set jobStatus for the Event. + * + * @param jobStatus the jobStatus value to set + * @return the JobStatusEventDetails object itself. + */ + public JobStatusEventDetails withJobStatus(String jobStatus) { + this.jobStatus = jobStatus; + return this; + } + + /** + * Get affectedObjectType for the event. + * + * @return the affectedObjectType value + */ + public String affectedObjectType() { + return this.affectedObjectType; + } + + /** + * Set affectedObjectType for the event. + * + * @param affectedObjectType the affectedObjectType value to set + * @return the JobStatusEventDetails object itself. + */ + public JobStatusEventDetails withAffectedObjectType(String affectedObjectType) { + this.affectedObjectType = affectedObjectType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobTaskDetails.java new file mode 100644 index 0000000000000..820720e577abe --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/JobTaskDetails.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents a task which is actually a workflow so that one can + * navigate to its individual drill down. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("JobTaskDetails") +public class JobTaskDetails extends TaskTypeDetails { + /** + * The job entity. + */ + @JsonProperty(value = "jobTask") + private JobEntity jobTask; + + /** + * Get the job entity. + * + * @return the jobTask value + */ + public JobEntity jobTask() { + return this.jobTask; + } + + /** + * Set the job entity. + * + * @param jobTask the jobTask value to set + * @return the JobTaskDetails object itself. + */ + public JobTaskDetails withJobTask(JobEntity jobTask) { + this.jobTask = jobTask; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/KeyEncryptionKeyInfo.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/KeyEncryptionKeyInfo.java new file mode 100644 index 0000000000000..10ac7fe64466f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/KeyEncryptionKeyInfo.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Key Encryption Key (KEK) information. + */ +public class KeyEncryptionKeyInfo { + /** + * The key url / identifier. + */ + @JsonProperty(value = "keyIdentifier") + private String keyIdentifier; + + /** + * The KeyVault resource ARM id for key. + */ + @JsonProperty(value = "keyVaultResourceArmId") + private String keyVaultResourceArmId; + + /** + * Get the key url / identifier. + * + * @return the keyIdentifier value + */ + public String keyIdentifier() { + return this.keyIdentifier; + } + + /** + * Set the key url / identifier. + * + * @param keyIdentifier the keyIdentifier value to set + * @return the KeyEncryptionKeyInfo object itself. + */ + public KeyEncryptionKeyInfo withKeyIdentifier(String keyIdentifier) { + this.keyIdentifier = keyIdentifier; + return this; + } + + /** + * Get the KeyVault resource ARM id for key. + * + * @return the keyVaultResourceArmId value + */ + public String keyVaultResourceArmId() { + return this.keyVaultResourceArmId; + } + + /** + * Set the KeyVault resource ARM id for key. + * + * @param keyVaultResourceArmId the keyVaultResourceArmId value to set + * @return the KeyEncryptionKeyInfo object itself. + */ + public KeyEncryptionKeyInfo withKeyVaultResourceArmId(String keyVaultResourceArmId) { + this.keyVaultResourceArmId = keyVaultResourceArmId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LicenseType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LicenseType.java new file mode 100644 index 0000000000000..995dd78e61595 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LicenseType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for LicenseType. + */ +public final class LicenseType extends ExpandableStringEnum { + /** Static value NotSpecified for LicenseType. */ + public static final LicenseType NOT_SPECIFIED = fromString("NotSpecified"); + + /** Static value NoLicenseType for LicenseType. */ + public static final LicenseType NO_LICENSE_TYPE = fromString("NoLicenseType"); + + /** Static value WindowsServer for LicenseType. */ + public static final LicenseType WINDOWS_SERVER = fromString("WindowsServer"); + + /** + * Creates or finds a LicenseType from its string representation. + * @param name a name to look for + * @return the corresponding LicenseType + */ + @JsonCreator + public static LicenseType fromString(String name) { + return fromString(name, LicenseType.class); + } + + /** + * @return known LicenseType values + */ + public static Collection values() { + return values(LicenseType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LogicalNetwork.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LogicalNetwork.java new file mode 100644 index 0000000000000..bd53360d11d6b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LogicalNetwork.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.LogicalNetworkInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing LogicalNetwork. + */ +public interface LogicalNetwork extends HasInner, Indexable, Refreshable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + LogicalNetworkProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LogicalNetworkProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LogicalNetworkProperties.java new file mode 100644 index 0000000000000..4644551aea6a8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/LogicalNetworkProperties.java @@ -0,0 +1,123 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Logical Network Properties. + */ +public class LogicalNetworkProperties { + /** + * The Friendly Name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * A value indicating whether Network Virtualization is enabled for the + * logical network. + */ + @JsonProperty(value = "networkVirtualizationStatus") + private String networkVirtualizationStatus; + + /** + * A value indicating whether logical network is used as private test + * network by test failover. + */ + @JsonProperty(value = "logicalNetworkUsage") + private String logicalNetworkUsage; + + /** + * A value indicating whether logical network definitions are isolated. + */ + @JsonProperty(value = "logicalNetworkDefinitionsStatus") + private String logicalNetworkDefinitionsStatus; + + /** + * Get the Friendly Name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the Friendly Name. + * + * @param friendlyName the friendlyName value to set + * @return the LogicalNetworkProperties object itself. + */ + public LogicalNetworkProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get a value indicating whether Network Virtualization is enabled for the logical network. + * + * @return the networkVirtualizationStatus value + */ + public String networkVirtualizationStatus() { + return this.networkVirtualizationStatus; + } + + /** + * Set a value indicating whether Network Virtualization is enabled for the logical network. + * + * @param networkVirtualizationStatus the networkVirtualizationStatus value to set + * @return the LogicalNetworkProperties object itself. + */ + public LogicalNetworkProperties withNetworkVirtualizationStatus(String networkVirtualizationStatus) { + this.networkVirtualizationStatus = networkVirtualizationStatus; + return this; + } + + /** + * Get a value indicating whether logical network is used as private test network by test failover. + * + * @return the logicalNetworkUsage value + */ + public String logicalNetworkUsage() { + return this.logicalNetworkUsage; + } + + /** + * Set a value indicating whether logical network is used as private test network by test failover. + * + * @param logicalNetworkUsage the logicalNetworkUsage value to set + * @return the LogicalNetworkProperties object itself. + */ + public LogicalNetworkProperties withLogicalNetworkUsage(String logicalNetworkUsage) { + this.logicalNetworkUsage = logicalNetworkUsage; + return this; + } + + /** + * Get a value indicating whether logical network definitions are isolated. + * + * @return the logicalNetworkDefinitionsStatus value + */ + public String logicalNetworkDefinitionsStatus() { + return this.logicalNetworkDefinitionsStatus; + } + + /** + * Set a value indicating whether logical network definitions are isolated. + * + * @param logicalNetworkDefinitionsStatus the logicalNetworkDefinitionsStatus value to set + * @return the LogicalNetworkProperties object itself. + */ + public LogicalNetworkProperties withLogicalNetworkDefinitionsStatus(String logicalNetworkDefinitionsStatus) { + this.logicalNetworkDefinitionsStatus = logicalNetworkDefinitionsStatus; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ManualActionTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ManualActionTaskDetails.java new file mode 100644 index 0000000000000..4a43c393951d5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ManualActionTaskDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the manual action task details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ManualActionTaskDetails") +public class ManualActionTaskDetails extends TaskTypeDetails { + /** + * The name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The instructions. + */ + @JsonProperty(value = "instructions") + private String instructions; + + /** + * The observation. + */ + @JsonProperty(value = "observation") + private String observation; + + /** + * Get the name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name. + * + * @param name the name value to set + * @return the ManualActionTaskDetails object itself. + */ + public ManualActionTaskDetails withName(String name) { + this.name = name; + return this; + } + + /** + * Get the instructions. + * + * @return the instructions value + */ + public String instructions() { + return this.instructions; + } + + /** + * Set the instructions. + * + * @param instructions the instructions value to set + * @return the ManualActionTaskDetails object itself. + */ + public ManualActionTaskDetails withInstructions(String instructions) { + this.instructions = instructions; + return this; + } + + /** + * Get the observation. + * + * @return the observation value + */ + public String observation() { + return this.observation; + } + + /** + * Set the observation. + * + * @param observation the observation value to set + * @return the ManualActionTaskDetails object itself. + */ + public ManualActionTaskDetails withObservation(String observation) { + this.observation = observation; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MasterTargetServer.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MasterTargetServer.java new file mode 100644 index 0000000000000..df9a923ef334b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MasterTargetServer.java @@ -0,0 +1,487 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Details of a Master Target Server. + */ +public class MasterTargetServer { + /** + * The server Id. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The IP address of the server. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The server name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The OS type of the server. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * The version of the scout component on the server. + */ + @JsonProperty(value = "agentVersion") + private String agentVersion; + + /** + * The last heartbeat received from the server. + */ + @JsonProperty(value = "lastHeartbeat") + private DateTime lastHeartbeat; + + /** + * Version status. + */ + @JsonProperty(value = "versionStatus") + private String versionStatus; + + /** + * The retention volumes of Master target Server. + */ + @JsonProperty(value = "retentionVolumes") + private List retentionVolumes; + + /** + * The list of data stores in the fabric. + */ + @JsonProperty(value = "dataStores") + private List dataStores; + + /** + * Validation errors. + */ + @JsonProperty(value = "validationErrors") + private List validationErrors; + + /** + * Health errors. + */ + @JsonProperty(value = "healthErrors") + private List healthErrors; + + /** + * Disk count of the master target. + */ + @JsonProperty(value = "diskCount") + private Integer diskCount; + + /** + * OS Version of the master target. + */ + @JsonProperty(value = "osVersion") + private String osVersion; + + /** + * Agent expiry date. + */ + @JsonProperty(value = "agentExpiryDate") + private DateTime agentExpiryDate; + + /** + * MARS agent version. + */ + @JsonProperty(value = "marsAgentVersion") + private String marsAgentVersion; + + /** + * MARS agent expiry date. + */ + @JsonProperty(value = "marsAgentExpiryDate") + private DateTime marsAgentExpiryDate; + + /** + * Agent version details. + */ + @JsonProperty(value = "agentVersionDetails") + private VersionDetails agentVersionDetails; + + /** + * Mars agent version details. + */ + @JsonProperty(value = "marsAgentVersionDetails") + private VersionDetails marsAgentVersionDetails; + + /** + * Get the server Id. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the server Id. + * + * @param id the id value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withId(String id) { + this.id = id; + return this; + } + + /** + * Get the IP address of the server. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the IP address of the server. + * + * @param ipAddress the ipAddress value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the server name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the server name. + * + * @param name the name value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withName(String name) { + this.name = name; + return this; + } + + /** + * Get the OS type of the server. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the OS type of the server. + * + * @param osType the osType value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get the version of the scout component on the server. + * + * @return the agentVersion value + */ + public String agentVersion() { + return this.agentVersion; + } + + /** + * Set the version of the scout component on the server. + * + * @param agentVersion the agentVersion value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withAgentVersion(String agentVersion) { + this.agentVersion = agentVersion; + return this; + } + + /** + * Get the last heartbeat received from the server. + * + * @return the lastHeartbeat value + */ + public DateTime lastHeartbeat() { + return this.lastHeartbeat; + } + + /** + * Set the last heartbeat received from the server. + * + * @param lastHeartbeat the lastHeartbeat value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withLastHeartbeat(DateTime lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + return this; + } + + /** + * Get version status. + * + * @return the versionStatus value + */ + public String versionStatus() { + return this.versionStatus; + } + + /** + * Set version status. + * + * @param versionStatus the versionStatus value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withVersionStatus(String versionStatus) { + this.versionStatus = versionStatus; + return this; + } + + /** + * Get the retention volumes of Master target Server. + * + * @return the retentionVolumes value + */ + public List retentionVolumes() { + return this.retentionVolumes; + } + + /** + * Set the retention volumes of Master target Server. + * + * @param retentionVolumes the retentionVolumes value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withRetentionVolumes(List retentionVolumes) { + this.retentionVolumes = retentionVolumes; + return this; + } + + /** + * Get the list of data stores in the fabric. + * + * @return the dataStores value + */ + public List dataStores() { + return this.dataStores; + } + + /** + * Set the list of data stores in the fabric. + * + * @param dataStores the dataStores value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withDataStores(List dataStores) { + this.dataStores = dataStores; + return this; + } + + /** + * Get validation errors. + * + * @return the validationErrors value + */ + public List validationErrors() { + return this.validationErrors; + } + + /** + * Set validation errors. + * + * @param validationErrors the validationErrors value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withValidationErrors(List validationErrors) { + this.validationErrors = validationErrors; + return this; + } + + /** + * Get health errors. + * + * @return the healthErrors value + */ + public List healthErrors() { + return this.healthErrors; + } + + /** + * Set health errors. + * + * @param healthErrors the healthErrors value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withHealthErrors(List healthErrors) { + this.healthErrors = healthErrors; + return this; + } + + /** + * Get disk count of the master target. + * + * @return the diskCount value + */ + public Integer diskCount() { + return this.diskCount; + } + + /** + * Set disk count of the master target. + * + * @param diskCount the diskCount value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withDiskCount(Integer diskCount) { + this.diskCount = diskCount; + return this; + } + + /** + * Get oS Version of the master target. + * + * @return the osVersion value + */ + public String osVersion() { + return this.osVersion; + } + + /** + * Set oS Version of the master target. + * + * @param osVersion the osVersion value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withOsVersion(String osVersion) { + this.osVersion = osVersion; + return this; + } + + /** + * Get agent expiry date. + * + * @return the agentExpiryDate value + */ + public DateTime agentExpiryDate() { + return this.agentExpiryDate; + } + + /** + * Set agent expiry date. + * + * @param agentExpiryDate the agentExpiryDate value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withAgentExpiryDate(DateTime agentExpiryDate) { + this.agentExpiryDate = agentExpiryDate; + return this; + } + + /** + * Get mARS agent version. + * + * @return the marsAgentVersion value + */ + public String marsAgentVersion() { + return this.marsAgentVersion; + } + + /** + * Set mARS agent version. + * + * @param marsAgentVersion the marsAgentVersion value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withMarsAgentVersion(String marsAgentVersion) { + this.marsAgentVersion = marsAgentVersion; + return this; + } + + /** + * Get mARS agent expiry date. + * + * @return the marsAgentExpiryDate value + */ + public DateTime marsAgentExpiryDate() { + return this.marsAgentExpiryDate; + } + + /** + * Set mARS agent expiry date. + * + * @param marsAgentExpiryDate the marsAgentExpiryDate value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withMarsAgentExpiryDate(DateTime marsAgentExpiryDate) { + this.marsAgentExpiryDate = marsAgentExpiryDate; + return this; + } + + /** + * Get agent version details. + * + * @return the agentVersionDetails value + */ + public VersionDetails agentVersionDetails() { + return this.agentVersionDetails; + } + + /** + * Set agent version details. + * + * @param agentVersionDetails the agentVersionDetails value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withAgentVersionDetails(VersionDetails agentVersionDetails) { + this.agentVersionDetails = agentVersionDetails; + return this; + } + + /** + * Get mars agent version details. + * + * @return the marsAgentVersionDetails value + */ + public VersionDetails marsAgentVersionDetails() { + return this.marsAgentVersionDetails; + } + + /** + * Set mars agent version details. + * + * @param marsAgentVersionDetails the marsAgentVersionDetails value to set + * @return the MasterTargetServer object itself. + */ + public MasterTargetServer withMarsAgentVersionDetails(VersionDetails marsAgentVersionDetails) { + this.marsAgentVersionDetails = marsAgentVersionDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateInput.java new file mode 100644 index 0000000000000..898e7bf0242e9 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input for migrate. + */ +public class MigrateInput { + /** + * Migrate input properties. + */ + @JsonProperty(value = "properties", required = true) + private MigrateInputProperties properties; + + /** + * Get migrate input properties. + * + * @return the properties value + */ + public MigrateInputProperties properties() { + return this.properties; + } + + /** + * Set migrate input properties. + * + * @param properties the properties value to set + * @return the MigrateInput object itself. + */ + public MigrateInput withProperties(MigrateInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateInputProperties.java new file mode 100644 index 0000000000000..431d13ab23719 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Migrate input properties. + */ +public class MigrateInputProperties { + /** + * The provider specific details. + */ + @JsonProperty(value = "providerSpecificDetails", required = true) + private MigrateProviderSpecificInput providerSpecificDetails; + + /** + * Get the provider specific details. + * + * @return the providerSpecificDetails value + */ + public MigrateProviderSpecificInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific details. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the MigrateInputProperties object itself. + */ + public MigrateInputProperties withProviderSpecificDetails(MigrateProviderSpecificInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateProviderSpecificInput.java new file mode 100644 index 0000000000000..3ade71df7af11 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrateProviderSpecificInput.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Migrate provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("MigrateProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "VMwareCbt", value = VMwareCbtMigrateInput.class) +}) +public class MigrateProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItem.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItem.java new file mode 100644 index 0000000000000..44c6f850e7e2e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItem.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.MigrationItemInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing MigrationItem. + */ +public interface MigrationItem extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + MigrationItemProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the MigrationItem definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithReplicationProtectionContainer, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of MigrationItem definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a MigrationItem definition. + */ + interface Blank extends WithReplicationProtectionContainer { + } + + /** + * The stage of the migrationitem definition allowing to specify ReplicationProtectionContainer. + */ + interface WithReplicationProtectionContainer { + /** + * Specifies fabricName, protectionContainerName. + * @param fabricName Fabric name + * @param protectionContainerName Protection container name + * @return the next definition stage + */ + WithProperties withExistingReplicationProtectionContainer(String fabricName, String protectionContainerName); + } + + /** + * The stage of the migrationitem definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Enable migration input properties + * @return the next definition stage + */ + WithCreate withProperties(EnableMigrationInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a MigrationItem update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of MigrationItem update stages. + */ + interface UpdateStages { + /** + * The stage of the migrationitem update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Update migration item input properties + * @return the next update stage + */ + Update withProperties(UpdateMigrationItemInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemOperation.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemOperation.java new file mode 100644 index 0000000000000..792390cb9c42e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemOperation.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for MigrationItemOperation. + */ +public final class MigrationItemOperation extends ExpandableStringEnum { + /** Static value DisableMigration for MigrationItemOperation. */ + public static final MigrationItemOperation DISABLE_MIGRATION = fromString("DisableMigration"); + + /** Static value TestMigrate for MigrationItemOperation. */ + public static final MigrationItemOperation TEST_MIGRATE = fromString("TestMigrate"); + + /** Static value TestMigrateCleanup for MigrationItemOperation. */ + public static final MigrationItemOperation TEST_MIGRATE_CLEANUP = fromString("TestMigrateCleanup"); + + /** Static value Migrate for MigrationItemOperation. */ + public static final MigrationItemOperation MIGRATE = fromString("Migrate"); + + /** + * Creates or finds a MigrationItemOperation from its string representation. + * @param name a name to look for + * @return the corresponding MigrationItemOperation + */ + @JsonCreator + public static MigrationItemOperation fromString(String name) { + return fromString(name, MigrationItemOperation.class); + } + + /** + * @return known MigrationItemOperation values + */ + public static Collection values() { + return values(MigrationItemOperation.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemProperties.java new file mode 100644 index 0000000000000..15e75144aa9af --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemProperties.java @@ -0,0 +1,231 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Migration item properties. + */ +public class MigrationItemProperties { + /** + * The on-premise virtual machine name. + */ + @JsonProperty(value = "machineName", access = JsonProperty.Access.WRITE_ONLY) + private String machineName; + + /** + * The ARM Id of policy governing this item. + */ + @JsonProperty(value = "policyId", access = JsonProperty.Access.WRITE_ONLY) + private String policyId; + + /** + * The name of policy governing this item. + */ + @JsonProperty(value = "policyFriendlyName", access = JsonProperty.Access.WRITE_ONLY) + private String policyFriendlyName; + + /** + * The recovery services provider ARM Id. + */ + @JsonProperty(value = "recoveryServicesProviderId", access = JsonProperty.Access.WRITE_ONLY) + private String recoveryServicesProviderId; + + /** + * The migration status. Possible values include: 'None', + * 'EnableMigrationInProgress', 'EnableMigrationFailed', + * 'DisableMigrationInProgress', 'DisableMigrationFailed', + * 'InitialSeedingInProgress', 'InitialSeedingFailed', 'Replicating', + * 'MigrationInProgress', 'MigrationSucceeded', 'MigrationFailed'. + */ + @JsonProperty(value = "migrationState", access = JsonProperty.Access.WRITE_ONLY) + private MigrationState migrationState; + + /** + * The migration state description. + */ + @JsonProperty(value = "migrationStateDescription", access = JsonProperty.Access.WRITE_ONLY) + private String migrationStateDescription; + + /** + * The test migrate state. Possible values include: 'None', + * 'TestMigrationInProgress', 'TestMigrationSucceeded', + * 'TestMigrationFailed', 'TestMigrationCleanupInProgress'. + */ + @JsonProperty(value = "testMigrateState", access = JsonProperty.Access.WRITE_ONLY) + private TestMigrationState testMigrateState; + + /** + * The test migrate state description. + */ + @JsonProperty(value = "testMigrateStateDescription", access = JsonProperty.Access.WRITE_ONLY) + private String testMigrateStateDescription; + + /** + * The consolidated health. + */ + @JsonProperty(value = "health", access = JsonProperty.Access.WRITE_ONLY) + private String health; + + /** + * The list of health errors. + */ + @JsonProperty(value = "healthErrors", access = JsonProperty.Access.WRITE_ONLY) + private List healthErrors; + + /** + * The allowed operations on the migration item, based on the current + * migration state of the item. + */ + @JsonProperty(value = "allowedOperations", access = JsonProperty.Access.WRITE_ONLY) + private List allowedOperations; + + /** + * The current job details. + */ + @JsonProperty(value = "currentJob", access = JsonProperty.Access.WRITE_ONLY) + private CurrentJobDetails currentJob; + + /** + * The migration provider custom settings. + */ + @JsonProperty(value = "providerSpecificDetails") + private MigrationProviderSpecificSettings providerSpecificDetails; + + /** + * Get the on-premise virtual machine name. + * + * @return the machineName value + */ + public String machineName() { + return this.machineName; + } + + /** + * Get the ARM Id of policy governing this item. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Get the name of policy governing this item. + * + * @return the policyFriendlyName value + */ + public String policyFriendlyName() { + return this.policyFriendlyName; + } + + /** + * Get the recovery services provider ARM Id. + * + * @return the recoveryServicesProviderId value + */ + public String recoveryServicesProviderId() { + return this.recoveryServicesProviderId; + } + + /** + * Get the migration status. Possible values include: 'None', 'EnableMigrationInProgress', 'EnableMigrationFailed', 'DisableMigrationInProgress', 'DisableMigrationFailed', 'InitialSeedingInProgress', 'InitialSeedingFailed', 'Replicating', 'MigrationInProgress', 'MigrationSucceeded', 'MigrationFailed'. + * + * @return the migrationState value + */ + public MigrationState migrationState() { + return this.migrationState; + } + + /** + * Get the migration state description. + * + * @return the migrationStateDescription value + */ + public String migrationStateDescription() { + return this.migrationStateDescription; + } + + /** + * Get the test migrate state. Possible values include: 'None', 'TestMigrationInProgress', 'TestMigrationSucceeded', 'TestMigrationFailed', 'TestMigrationCleanupInProgress'. + * + * @return the testMigrateState value + */ + public TestMigrationState testMigrateState() { + return this.testMigrateState; + } + + /** + * Get the test migrate state description. + * + * @return the testMigrateStateDescription value + */ + public String testMigrateStateDescription() { + return this.testMigrateStateDescription; + } + + /** + * Get the consolidated health. + * + * @return the health value + */ + public String health() { + return this.health; + } + + /** + * Get the list of health errors. + * + * @return the healthErrors value + */ + public List healthErrors() { + return this.healthErrors; + } + + /** + * Get the allowed operations on the migration item, based on the current migration state of the item. + * + * @return the allowedOperations value + */ + public List allowedOperations() { + return this.allowedOperations; + } + + /** + * Get the current job details. + * + * @return the currentJob value + */ + public CurrentJobDetails currentJob() { + return this.currentJob; + } + + /** + * Get the migration provider custom settings. + * + * @return the providerSpecificDetails value + */ + public MigrationProviderSpecificSettings providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the migration provider custom settings. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the MigrationItemProperties object itself. + */ + public MigrationItemProperties withProviderSpecificDetails(MigrationProviderSpecificSettings providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemsQueryParameter.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemsQueryParameter.java new file mode 100644 index 0000000000000..24ef28725f3f7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationItemsQueryParameter.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Query parameter to enumerate migration items. + */ +public class MigrationItemsQueryParameter { + /** + * The source fabric name filter. + */ + @JsonProperty(value = "sourceFabricName") + private String sourceFabricName; + + /** + * The replication provider type. + */ + @JsonProperty(value = "instanceType") + private String instanceType; + + /** + * Get the source fabric name filter. + * + * @return the sourceFabricName value + */ + public String sourceFabricName() { + return this.sourceFabricName; + } + + /** + * Set the source fabric name filter. + * + * @param sourceFabricName the sourceFabricName value to set + * @return the MigrationItemsQueryParameter object itself. + */ + public MigrationItemsQueryParameter withSourceFabricName(String sourceFabricName) { + this.sourceFabricName = sourceFabricName; + return this; + } + + /** + * Get the replication provider type. + * + * @return the instanceType value + */ + public String instanceType() { + return this.instanceType; + } + + /** + * Set the replication provider type. + * + * @param instanceType the instanceType value to set + * @return the MigrationItemsQueryParameter object itself. + */ + public MigrationItemsQueryParameter withInstanceType(String instanceType) { + this.instanceType = instanceType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationProviderSpecificSettings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationProviderSpecificSettings.java new file mode 100644 index 0000000000000..429e4c642eb24 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationProviderSpecificSettings.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Migration provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("MigrationProviderSpecificSettings") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "VMwareCbt", value = VMwareCbtMigrationDetails.class) +}) +public class MigrationProviderSpecificSettings { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPoint.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPoint.java new file mode 100644 index 0000000000000..70b43702153b1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPoint.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.MigrationRecoveryPointInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing MigrationRecoveryPoint. + */ +public interface MigrationRecoveryPoint extends HasInner, Indexable, Refreshable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + MigrationRecoveryPointProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPointProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPointProperties.java new file mode 100644 index 0000000000000..b5fdcd77f9397 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPointProperties.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Migration item recovery point properties. + */ +public class MigrationRecoveryPointProperties { + /** + * The recovery point time. + */ + @JsonProperty(value = "recoveryPointTime", access = JsonProperty.Access.WRITE_ONLY) + private DateTime recoveryPointTime; + + /** + * The recovery point type. Possible values include: 'NotSpecified', + * 'ApplicationConsistent', 'CrashConsistent'. + */ + @JsonProperty(value = "recoveryPointType", access = JsonProperty.Access.WRITE_ONLY) + private MigrationRecoveryPointType recoveryPointType; + + /** + * Get the recovery point time. + * + * @return the recoveryPointTime value + */ + public DateTime recoveryPointTime() { + return this.recoveryPointTime; + } + + /** + * Get the recovery point type. Possible values include: 'NotSpecified', 'ApplicationConsistent', 'CrashConsistent'. + * + * @return the recoveryPointType value + */ + public MigrationRecoveryPointType recoveryPointType() { + return this.recoveryPointType; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPointType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPointType.java new file mode 100644 index 0000000000000..d1f8ffa257e46 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPointType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for MigrationRecoveryPointType. + */ +public final class MigrationRecoveryPointType extends ExpandableStringEnum { + /** Static value NotSpecified for MigrationRecoveryPointType. */ + public static final MigrationRecoveryPointType NOT_SPECIFIED = fromString("NotSpecified"); + + /** Static value ApplicationConsistent for MigrationRecoveryPointType. */ + public static final MigrationRecoveryPointType APPLICATION_CONSISTENT = fromString("ApplicationConsistent"); + + /** Static value CrashConsistent for MigrationRecoveryPointType. */ + public static final MigrationRecoveryPointType CRASH_CONSISTENT = fromString("CrashConsistent"); + + /** + * Creates or finds a MigrationRecoveryPointType from its string representation. + * @param name a name to look for + * @return the corresponding MigrationRecoveryPointType + */ + @JsonCreator + public static MigrationRecoveryPointType fromString(String name) { + return fromString(name, MigrationRecoveryPointType.class); + } + + /** + * @return known MigrationRecoveryPointType values + */ + public static Collection values() { + return values(MigrationRecoveryPointType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPoints.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPoints.java new file mode 100644 index 0000000000000..70e62e8119f67 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationRecoveryPoints.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.MigrationRecoveryPointsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing MigrationRecoveryPoints. + */ +public interface MigrationRecoveryPoints extends HasInner { + /** + * Gets a recovery point for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param migrationRecoveryPointName The migration recovery point name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String protectionContainerName, String migrationItemName, String migrationRecoveryPointName); + + /** + * Gets the recovery points for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationMigrationItemsAsync(final String fabricName, final String protectionContainerName, final String migrationItemName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationState.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationState.java new file mode 100644 index 0000000000000..70a4134a9d706 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MigrationState.java @@ -0,0 +1,68 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for MigrationState. + */ +public final class MigrationState extends ExpandableStringEnum { + /** Static value None for MigrationState. */ + public static final MigrationState NONE = fromString("None"); + + /** Static value EnableMigrationInProgress for MigrationState. */ + public static final MigrationState ENABLE_MIGRATION_IN_PROGRESS = fromString("EnableMigrationInProgress"); + + /** Static value EnableMigrationFailed for MigrationState. */ + public static final MigrationState ENABLE_MIGRATION_FAILED = fromString("EnableMigrationFailed"); + + /** Static value DisableMigrationInProgress for MigrationState. */ + public static final MigrationState DISABLE_MIGRATION_IN_PROGRESS = fromString("DisableMigrationInProgress"); + + /** Static value DisableMigrationFailed for MigrationState. */ + public static final MigrationState DISABLE_MIGRATION_FAILED = fromString("DisableMigrationFailed"); + + /** Static value InitialSeedingInProgress for MigrationState. */ + public static final MigrationState INITIAL_SEEDING_IN_PROGRESS = fromString("InitialSeedingInProgress"); + + /** Static value InitialSeedingFailed for MigrationState. */ + public static final MigrationState INITIAL_SEEDING_FAILED = fromString("InitialSeedingFailed"); + + /** Static value Replicating for MigrationState. */ + public static final MigrationState REPLICATING = fromString("Replicating"); + + /** Static value MigrationInProgress for MigrationState. */ + public static final MigrationState MIGRATION_IN_PROGRESS = fromString("MigrationInProgress"); + + /** Static value MigrationSucceeded for MigrationState. */ + public static final MigrationState MIGRATION_SUCCEEDED = fromString("MigrationSucceeded"); + + /** Static value MigrationFailed for MigrationState. */ + public static final MigrationState MIGRATION_FAILED = fromString("MigrationFailed"); + + /** + * Creates or finds a MigrationState from its string representation. + * @param name a name to look for + * @return the corresponding MigrationState + */ + @JsonCreator + public static MigrationState fromString(String name) { + return fromString(name, MigrationState.class); + } + + /** + * @return known MigrationState values + */ + public static Collection values() { + return values(MigrationState.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MobilityServiceUpdate.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MobilityServiceUpdate.java new file mode 100644 index 0000000000000..650d9681bd111 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MobilityServiceUpdate.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The Mobility Service update details. + */ +public class MobilityServiceUpdate { + /** + * The version of the latest update. + */ + @JsonProperty(value = "version") + private String version; + + /** + * The reboot status of the update - whether it is required or not. + */ + @JsonProperty(value = "rebootStatus") + private String rebootStatus; + + /** + * The OS type. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * Get the version of the latest update. + * + * @return the version value + */ + public String version() { + return this.version; + } + + /** + * Set the version of the latest update. + * + * @param version the version value to set + * @return the MobilityServiceUpdate object itself. + */ + public MobilityServiceUpdate withVersion(String version) { + this.version = version; + return this; + } + + /** + * Get the reboot status of the update - whether it is required or not. + * + * @return the rebootStatus value + */ + public String rebootStatus() { + return this.rebootStatus; + } + + /** + * Set the reboot status of the update - whether it is required or not. + * + * @param rebootStatus the rebootStatus value to set + * @return the MobilityServiceUpdate object itself. + */ + public MobilityServiceUpdate withRebootStatus(String rebootStatus) { + this.rebootStatus = rebootStatus; + return this; + } + + /** + * Get the OS type. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the OS type. + * + * @param osType the osType value to set + * @return the MobilityServiceUpdate object itself. + */ + public MobilityServiceUpdate withOsType(String osType) { + this.osType = osType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmGroupCreateOption.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmGroupCreateOption.java new file mode 100644 index 0000000000000..b355fd10f41fd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmGroupCreateOption.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for MultiVmGroupCreateOption. + */ +public final class MultiVmGroupCreateOption extends ExpandableStringEnum { + /** Static value AutoCreated for MultiVmGroupCreateOption. */ + public static final MultiVmGroupCreateOption AUTO_CREATED = fromString("AutoCreated"); + + /** Static value UserSpecified for MultiVmGroupCreateOption. */ + public static final MultiVmGroupCreateOption USER_SPECIFIED = fromString("UserSpecified"); + + /** + * Creates or finds a MultiVmGroupCreateOption from its string representation. + * @param name a name to look for + * @return the corresponding MultiVmGroupCreateOption + */ + @JsonCreator + public static MultiVmGroupCreateOption fromString(String name) { + return fromString(name, MultiVmGroupCreateOption.class); + } + + /** + * @return known MultiVmGroupCreateOption values + */ + public static Collection values() { + return values(MultiVmGroupCreateOption.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmSyncPointOption.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmSyncPointOption.java new file mode 100644 index 0000000000000..c39aacfcba51f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmSyncPointOption.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for MultiVmSyncPointOption. + */ +public final class MultiVmSyncPointOption extends ExpandableStringEnum { + /** Static value UseMultiVmSyncRecoveryPoint for MultiVmSyncPointOption. */ + public static final MultiVmSyncPointOption USE_MULTI_VM_SYNC_RECOVERY_POINT = fromString("UseMultiVmSyncRecoveryPoint"); + + /** Static value UsePerVmRecoveryPoint for MultiVmSyncPointOption. */ + public static final MultiVmSyncPointOption USE_PER_VM_RECOVERY_POINT = fromString("UsePerVmRecoveryPoint"); + + /** + * Creates or finds a MultiVmSyncPointOption from its string representation. + * @param name a name to look for + * @return the corresponding MultiVmSyncPointOption + */ + @JsonCreator + public static MultiVmSyncPointOption fromString(String name) { + return fromString(name, MultiVmSyncPointOption.class); + } + + /** + * @return known MultiVmSyncPointOption values + */ + public static Collection values() { + return values(MultiVmSyncPointOption.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmSyncStatus.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmSyncStatus.java new file mode 100644 index 0000000000000..86e4085a4e1e1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/MultiVmSyncStatus.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for MultiVmSyncStatus. + */ +public final class MultiVmSyncStatus extends ExpandableStringEnum { + /** Static value Enabled for MultiVmSyncStatus. */ + public static final MultiVmSyncStatus ENABLED = fromString("Enabled"); + + /** Static value Disabled for MultiVmSyncStatus. */ + public static final MultiVmSyncStatus DISABLED = fromString("Disabled"); + + /** + * Creates or finds a MultiVmSyncStatus from its string representation. + * @param name a name to look for + * @return the corresponding MultiVmSyncStatus + */ + @JsonCreator + public static MultiVmSyncStatus fromString(String name) { + return fromString(name, MultiVmSyncStatus.class); + } + + /** + * @return known MultiVmSyncStatus values + */ + public static Collection values() { + return values(MultiVmSyncStatus.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Network.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Network.java new file mode 100644 index 0000000000000..f4f764f496cd6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Network.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.NetworkInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing Network. + */ +public interface Network extends HasInner, Indexable, Refreshable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + NetworkProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMapping.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMapping.java new file mode 100644 index 0000000000000..ede0249dbfd6c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMapping.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.NetworkMappingInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing NetworkMapping. + */ +public interface NetworkMapping extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + NetworkMappingProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the NetworkMapping definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithReplicationNetwork, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of NetworkMapping definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a NetworkMapping definition. + */ + interface Blank extends WithReplicationNetwork { + } + + /** + * The stage of the networkmapping definition allowing to specify ReplicationNetwork. + */ + interface WithReplicationNetwork { + /** + * Specifies fabricName, networkName. + * @param fabricName Primary fabric name + * @param networkName Primary network name + * @return the next definition stage + */ + WithProperties withExistingReplicationNetwork(String fabricName, String networkName); + } + + /** + * The stage of the networkmapping definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Input properties for creating network mapping + * @return the next definition stage + */ + WithCreate withProperties(CreateNetworkMappingInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a NetworkMapping update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of NetworkMapping update stages. + */ + interface UpdateStages { + /** + * The stage of the networkmapping update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties The input properties needed to update network mapping + * @return the next update stage + */ + Update withProperties(UpdateNetworkMappingInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMappingFabricSpecificSettings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMappingFabricSpecificSettings.java new file mode 100644 index 0000000000000..ebfa1d71151ce --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMappingFabricSpecificSettings.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Network Mapping fabric specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("NetworkMappingFabricSpecificSettings") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "AzureToAzure", value = AzureToAzureNetworkMappingSettings.class), + @JsonSubTypes.Type(name = "VmmToAzure", value = VmmToAzureNetworkMappingSettings.class), + @JsonSubTypes.Type(name = "VmmToVmm", value = VmmToVmmNetworkMappingSettings.class) +}) +public class NetworkMappingFabricSpecificSettings { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMappingProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMappingProperties.java new file mode 100644 index 0000000000000..bd1fc2be3d289 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkMappingProperties.java @@ -0,0 +1,251 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Network Mapping Properties. + */ +public class NetworkMappingProperties { + /** + * The pairing state for network mapping. + */ + @JsonProperty(value = "state") + private String state; + + /** + * The primary network friendly name. + */ + @JsonProperty(value = "primaryNetworkFriendlyName") + private String primaryNetworkFriendlyName; + + /** + * The primary network id for network mapping. + */ + @JsonProperty(value = "primaryNetworkId") + private String primaryNetworkId; + + /** + * The primary fabric friendly name. + */ + @JsonProperty(value = "primaryFabricFriendlyName") + private String primaryFabricFriendlyName; + + /** + * The recovery network friendly name. + */ + @JsonProperty(value = "recoveryNetworkFriendlyName") + private String recoveryNetworkFriendlyName; + + /** + * The recovery network id for network mapping. + */ + @JsonProperty(value = "recoveryNetworkId") + private String recoveryNetworkId; + + /** + * The recovery fabric ARM id. + */ + @JsonProperty(value = "recoveryFabricArmId") + private String recoveryFabricArmId; + + /** + * The recovery fabric friendly name. + */ + @JsonProperty(value = "recoveryFabricFriendlyName") + private String recoveryFabricFriendlyName; + + /** + * The fabric specific settings. + */ + @JsonProperty(value = "fabricSpecificSettings") + private NetworkMappingFabricSpecificSettings fabricSpecificSettings; + + /** + * Get the pairing state for network mapping. + * + * @return the state value + */ + public String state() { + return this.state; + } + + /** + * Set the pairing state for network mapping. + * + * @param state the state value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withState(String state) { + this.state = state; + return this; + } + + /** + * Get the primary network friendly name. + * + * @return the primaryNetworkFriendlyName value + */ + public String primaryNetworkFriendlyName() { + return this.primaryNetworkFriendlyName; + } + + /** + * Set the primary network friendly name. + * + * @param primaryNetworkFriendlyName the primaryNetworkFriendlyName value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withPrimaryNetworkFriendlyName(String primaryNetworkFriendlyName) { + this.primaryNetworkFriendlyName = primaryNetworkFriendlyName; + return this; + } + + /** + * Get the primary network id for network mapping. + * + * @return the primaryNetworkId value + */ + public String primaryNetworkId() { + return this.primaryNetworkId; + } + + /** + * Set the primary network id for network mapping. + * + * @param primaryNetworkId the primaryNetworkId value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withPrimaryNetworkId(String primaryNetworkId) { + this.primaryNetworkId = primaryNetworkId; + return this; + } + + /** + * Get the primary fabric friendly name. + * + * @return the primaryFabricFriendlyName value + */ + public String primaryFabricFriendlyName() { + return this.primaryFabricFriendlyName; + } + + /** + * Set the primary fabric friendly name. + * + * @param primaryFabricFriendlyName the primaryFabricFriendlyName value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withPrimaryFabricFriendlyName(String primaryFabricFriendlyName) { + this.primaryFabricFriendlyName = primaryFabricFriendlyName; + return this; + } + + /** + * Get the recovery network friendly name. + * + * @return the recoveryNetworkFriendlyName value + */ + public String recoveryNetworkFriendlyName() { + return this.recoveryNetworkFriendlyName; + } + + /** + * Set the recovery network friendly name. + * + * @param recoveryNetworkFriendlyName the recoveryNetworkFriendlyName value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withRecoveryNetworkFriendlyName(String recoveryNetworkFriendlyName) { + this.recoveryNetworkFriendlyName = recoveryNetworkFriendlyName; + return this; + } + + /** + * Get the recovery network id for network mapping. + * + * @return the recoveryNetworkId value + */ + public String recoveryNetworkId() { + return this.recoveryNetworkId; + } + + /** + * Set the recovery network id for network mapping. + * + * @param recoveryNetworkId the recoveryNetworkId value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withRecoveryNetworkId(String recoveryNetworkId) { + this.recoveryNetworkId = recoveryNetworkId; + return this; + } + + /** + * Get the recovery fabric ARM id. + * + * @return the recoveryFabricArmId value + */ + public String recoveryFabricArmId() { + return this.recoveryFabricArmId; + } + + /** + * Set the recovery fabric ARM id. + * + * @param recoveryFabricArmId the recoveryFabricArmId value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withRecoveryFabricArmId(String recoveryFabricArmId) { + this.recoveryFabricArmId = recoveryFabricArmId; + return this; + } + + /** + * Get the recovery fabric friendly name. + * + * @return the recoveryFabricFriendlyName value + */ + public String recoveryFabricFriendlyName() { + return this.recoveryFabricFriendlyName; + } + + /** + * Set the recovery fabric friendly name. + * + * @param recoveryFabricFriendlyName the recoveryFabricFriendlyName value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withRecoveryFabricFriendlyName(String recoveryFabricFriendlyName) { + this.recoveryFabricFriendlyName = recoveryFabricFriendlyName; + return this; + } + + /** + * Get the fabric specific settings. + * + * @return the fabricSpecificSettings value + */ + public NetworkMappingFabricSpecificSettings fabricSpecificSettings() { + return this.fabricSpecificSettings; + } + + /** + * Set the fabric specific settings. + * + * @param fabricSpecificSettings the fabricSpecificSettings value to set + * @return the NetworkMappingProperties object itself. + */ + public NetworkMappingProperties withFabricSpecificSettings(NetworkMappingFabricSpecificSettings fabricSpecificSettings) { + this.fabricSpecificSettings = fabricSpecificSettings; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkProperties.java new file mode 100644 index 0000000000000..968cee888a154 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/NetworkProperties.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Network Properties. + */ +public class NetworkProperties { + /** + * The Fabric Type. + */ + @JsonProperty(value = "fabricType") + private String fabricType; + + /** + * The List of subnets. + */ + @JsonProperty(value = "subnets") + private List subnets; + + /** + * The Friendly Name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The Network Type. + */ + @JsonProperty(value = "networkType") + private String networkType; + + /** + * Get the Fabric Type. + * + * @return the fabricType value + */ + public String fabricType() { + return this.fabricType; + } + + /** + * Set the Fabric Type. + * + * @param fabricType the fabricType value to set + * @return the NetworkProperties object itself. + */ + public NetworkProperties withFabricType(String fabricType) { + this.fabricType = fabricType; + return this; + } + + /** + * Get the List of subnets. + * + * @return the subnets value + */ + public List subnets() { + return this.subnets; + } + + /** + * Set the List of subnets. + * + * @param subnets the subnets value to set + * @return the NetworkProperties object itself. + */ + public NetworkProperties withSubnets(List subnets) { + this.subnets = subnets; + return this; + } + + /** + * Get the Friendly Name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the Friendly Name. + * + * @param friendlyName the friendlyName value to set + * @return the NetworkProperties object itself. + */ + public NetworkProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the Network Type. + * + * @return the networkType value + */ + public String networkType() { + return this.networkType; + } + + /** + * Set the Network Type. + * + * @param networkType the networkType value to set + * @return the NetworkProperties object itself. + */ + public NetworkProperties withNetworkType(String networkType) { + this.networkType = networkType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OSDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OSDetails.java new file mode 100644 index 0000000000000..a7e4ebe732d10 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OSDetails.java @@ -0,0 +1,173 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Disk Details. + */ +public class OSDetails { + /** + * VM Disk details. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * Product type. + */ + @JsonProperty(value = "productType") + private String productType; + + /** + * The OSEdition. + */ + @JsonProperty(value = "osEdition") + private String osEdition; + + /** + * The OS Version. + */ + @JsonProperty(value = "oSVersion") + private String oSVersion; + + /** + * The OS Major Version. + */ + @JsonProperty(value = "oSMajorVersion") + private String oSMajorVersion; + + /** + * The OS Minor Version. + */ + @JsonProperty(value = "oSMinorVersion") + private String oSMinorVersion; + + /** + * Get vM Disk details. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set vM Disk details. + * + * @param osType the osType value to set + * @return the OSDetails object itself. + */ + public OSDetails withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get product type. + * + * @return the productType value + */ + public String productType() { + return this.productType; + } + + /** + * Set product type. + * + * @param productType the productType value to set + * @return the OSDetails object itself. + */ + public OSDetails withProductType(String productType) { + this.productType = productType; + return this; + } + + /** + * Get the OSEdition. + * + * @return the osEdition value + */ + public String osEdition() { + return this.osEdition; + } + + /** + * Set the OSEdition. + * + * @param osEdition the osEdition value to set + * @return the OSDetails object itself. + */ + public OSDetails withOsEdition(String osEdition) { + this.osEdition = osEdition; + return this; + } + + /** + * Get the OS Version. + * + * @return the oSVersion value + */ + public String oSVersion() { + return this.oSVersion; + } + + /** + * Set the OS Version. + * + * @param oSVersion the oSVersion value to set + * @return the OSDetails object itself. + */ + public OSDetails withOSVersion(String oSVersion) { + this.oSVersion = oSVersion; + return this; + } + + /** + * Get the OS Major Version. + * + * @return the oSMajorVersion value + */ + public String oSMajorVersion() { + return this.oSMajorVersion; + } + + /** + * Set the OS Major Version. + * + * @param oSMajorVersion the oSMajorVersion value to set + * @return the OSDetails object itself. + */ + public OSDetails withOSMajorVersion(String oSMajorVersion) { + this.oSMajorVersion = oSMajorVersion; + return this; + } + + /** + * Get the OS Minor Version. + * + * @return the oSMinorVersion value + */ + public String oSMinorVersion() { + return this.oSMinorVersion; + } + + /** + * Set the OS Minor Version. + * + * @param oSMinorVersion the oSMinorVersion value to set + * @return the OSDetails object itself. + */ + public OSDetails withOSMinorVersion(String oSMinorVersion) { + this.oSMinorVersion = oSMinorVersion; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OSDiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OSDiskDetails.java new file mode 100644 index 0000000000000..c653d30205585 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OSDiskDetails.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Details of the OS Disk. + */ +public class OSDiskDetails { + /** + * The id of the disk containing the OS. + */ + @JsonProperty(value = "osVhdId") + private String osVhdId; + + /** + * The type of the OS on the VM. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * The OS disk VHD name. + */ + @JsonProperty(value = "vhdName") + private String vhdName; + + /** + * Get the id of the disk containing the OS. + * + * @return the osVhdId value + */ + public String osVhdId() { + return this.osVhdId; + } + + /** + * Set the id of the disk containing the OS. + * + * @param osVhdId the osVhdId value to set + * @return the OSDiskDetails object itself. + */ + public OSDiskDetails withOsVhdId(String osVhdId) { + this.osVhdId = osVhdId; + return this; + } + + /** + * Get the type of the OS on the VM. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the type of the OS on the VM. + * + * @param osType the osType value to set + * @return the OSDiskDetails object itself. + */ + public OSDiskDetails withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get the OS disk VHD name. + * + * @return the vhdName value + */ + public String vhdName() { + return this.vhdName; + } + + /** + * Set the OS disk VHD name. + * + * @param vhdName the vhdName value to set + * @return the OSDiskDetails object itself. + */ + public OSDiskDetails withVhdName(String vhdName) { + this.vhdName = vhdName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Operations.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Operations.java new file mode 100644 index 0000000000000..47c7da7c24b03 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Operations.java @@ -0,0 +1,19 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsListing; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.OperationsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Operations. + */ +public interface Operations extends SupportsListing, HasInner { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OperationsDiscovery.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OperationsDiscovery.java new file mode 100644 index 0000000000000..fb28280913a70 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/OperationsDiscovery.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.OperationsDiscoveryInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing OperationsDiscovery. + */ +public interface OperationsDiscovery extends HasInner, HasManager { + /** + * @return the display value. + */ + Display display(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the origin value. + */ + String origin(); + + /** + * @return the properties value. + */ + Object properties(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PlannedFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PlannedFailoverInput.java new file mode 100644 index 0000000000000..271d92881ffc9 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PlannedFailoverInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input definition for planned failover. + */ +public class PlannedFailoverInput { + /** + * Planned failover input properties. + */ + @JsonProperty(value = "properties") + private PlannedFailoverInputProperties properties; + + /** + * Get planned failover input properties. + * + * @return the properties value + */ + public PlannedFailoverInputProperties properties() { + return this.properties; + } + + /** + * Set planned failover input properties. + * + * @param properties the properties value to set + * @return the PlannedFailoverInput object itself. + */ + public PlannedFailoverInput withProperties(PlannedFailoverInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PlannedFailoverInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PlannedFailoverInputProperties.java new file mode 100644 index 0000000000000..44b558ce9cde6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PlannedFailoverInputProperties.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input definition for planned failover input properties. + */ +public class PlannedFailoverInputProperties { + /** + * Failover direction. + */ + @JsonProperty(value = "failoverDirection") + private String failoverDirection; + + /** + * Provider specific settings. + */ + @JsonProperty(value = "providerSpecificDetails") + private ProviderSpecificFailoverInput providerSpecificDetails; + + /** + * Get failover direction. + * + * @return the failoverDirection value + */ + public String failoverDirection() { + return this.failoverDirection; + } + + /** + * Set failover direction. + * + * @param failoverDirection the failoverDirection value to set + * @return the PlannedFailoverInputProperties object itself. + */ + public PlannedFailoverInputProperties withFailoverDirection(String failoverDirection) { + this.failoverDirection = failoverDirection; + return this; + } + + /** + * Get provider specific settings. + * + * @return the providerSpecificDetails value + */ + public ProviderSpecificFailoverInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set provider specific settings. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the PlannedFailoverInputProperties object itself. + */ + public PlannedFailoverInputProperties withProviderSpecificDetails(ProviderSpecificFailoverInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Policy.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Policy.java new file mode 100644 index 0000000000000..4832ecb292bcc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Policy.java @@ -0,0 +1,120 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.PolicyInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing Policy. + */ +public interface Policy extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + PolicyProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the Policy definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithVault, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of Policy definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a Policy definition. + */ + interface Blank extends WithVault { + } + + /** + * The stage of the policy definition allowing to specify Vault. + */ + interface WithVault { + /** + * Specifies . + * @return the next definition stage + */ + WithProperties withExistingVault(); + } + + /** + * The stage of the policy definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Policy creation properties + * @return the next definition stage + */ + WithCreate withProperties(CreatePolicyInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a Policy update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of Policy update stages. + */ + interface UpdateStages { + /** + * The stage of the policy update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties The ReplicationProviderSettings + * @return the next update stage + */ + Update withProperties(UpdatePolicyInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProperties.java new file mode 100644 index 0000000000000..1588d7b813ea7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProperties.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Protection profile custom data details. + */ +public class PolicyProperties { + /** + * The FriendlyName. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The ReplicationChannelSetting. + */ + @JsonProperty(value = "providerSpecificDetails") + private PolicyProviderSpecificDetails providerSpecificDetails; + + /** + * Get the FriendlyName. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the FriendlyName. + * + * @param friendlyName the friendlyName value to set + * @return the PolicyProperties object itself. + */ + public PolicyProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the ReplicationChannelSetting. + * + * @return the providerSpecificDetails value + */ + public PolicyProviderSpecificDetails providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the ReplicationChannelSetting. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the PolicyProperties object itself. + */ + public PolicyProperties withProviderSpecificDetails(PolicyProviderSpecificDetails providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProviderSpecificDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProviderSpecificDetails.java new file mode 100644 index 0000000000000..805c358347b8f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProviderSpecificDetails.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Base class for Provider specific details for policies. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("PolicyProviderSpecificDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2APolicyDetails.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzurePolicyDetails.class), + @JsonSubTypes.Type(name = "HyperVReplicaBasePolicyDetails", value = HyperVReplicaBasePolicyDetails.class), + @JsonSubTypes.Type(name = "HyperVReplica2012R2", value = HyperVReplicaBluePolicyDetails.class), + @JsonSubTypes.Type(name = "HyperVReplica2012", value = HyperVReplicaPolicyDetails.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2PolicyDetails.class), + @JsonSubTypes.Type(name = "InMageBasePolicyDetails", value = InMageBasePolicyDetails.class), + @JsonSubTypes.Type(name = "InMage", value = InMagePolicyDetails.class), + @JsonSubTypes.Type(name = "RcmAzureMigration", value = RcmAzureMigrationPolicyDetails.class), + @JsonSubTypes.Type(name = "VMwareCbt", value = VmwareCbtPolicyDetails.class) +}) +public class PolicyProviderSpecificDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProviderSpecificInput.java new file mode 100644 index 0000000000000..d81e30898a806 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PolicyProviderSpecificInput.java @@ -0,0 +1,30 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Base class for provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("PolicyProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2APolicyCreationInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzurePolicyInput.class), + @JsonSubTypes.Type(name = "HyperVReplica2012R2", value = HyperVReplicaBluePolicyInput.class), + @JsonSubTypes.Type(name = "HyperVReplica2012", value = HyperVReplicaPolicyInput.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2PolicyInput.class), + @JsonSubTypes.Type(name = "InMage", value = InMagePolicyInput.class), + @JsonSubTypes.Type(name = "VMwareCbt", value = VMwareCbtPolicyCreationInput.class) +}) +public class PolicyProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PossibleOperationsDirections.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PossibleOperationsDirections.java new file mode 100644 index 0000000000000..4cbd7e7233b23 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PossibleOperationsDirections.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for PossibleOperationsDirections. + */ +public final class PossibleOperationsDirections extends ExpandableStringEnum { + /** Static value PrimaryToRecovery for PossibleOperationsDirections. */ + public static final PossibleOperationsDirections PRIMARY_TO_RECOVERY = fromString("PrimaryToRecovery"); + + /** Static value RecoveryToPrimary for PossibleOperationsDirections. */ + public static final PossibleOperationsDirections RECOVERY_TO_PRIMARY = fromString("RecoveryToPrimary"); + + /** + * Creates or finds a PossibleOperationsDirections from its string representation. + * @param name a name to look for + * @return the corresponding PossibleOperationsDirections + */ + @JsonCreator + public static PossibleOperationsDirections fromString(String name) { + return fromString(name, PossibleOperationsDirections.class); + } + + /** + * @return known PossibleOperationsDirections values + */ + public static Collection values() { + return values(PossibleOperationsDirections.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PresenceStatus.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PresenceStatus.java new file mode 100644 index 0000000000000..9f061cff31aa6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/PresenceStatus.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for PresenceStatus. + */ +public final class PresenceStatus extends ExpandableStringEnum { + /** Static value Unknown for PresenceStatus. */ + public static final PresenceStatus UNKNOWN = fromString("Unknown"); + + /** Static value Present for PresenceStatus. */ + public static final PresenceStatus PRESENT = fromString("Present"); + + /** Static value NotPresent for PresenceStatus. */ + public static final PresenceStatus NOT_PRESENT = fromString("NotPresent"); + + /** + * Creates or finds a PresenceStatus from its string representation. + * @param name a name to look for + * @return the corresponding PresenceStatus + */ + @JsonCreator + public static PresenceStatus fromString(String name) { + return fromString(name, PresenceStatus.class); + } + + /** + * @return known PresenceStatus values + */ + public static Collection values() { + return values(PresenceStatus.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProcessServer.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProcessServer.java new file mode 100644 index 0000000000000..1f51e1e5febba --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProcessServer.java @@ -0,0 +1,749 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Details of the Process Server. + */ +public class ProcessServer { + /** + * The Process Server's friendly name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The Process Server Id. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The IP address of the server. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The OS type of the server. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * The version of the scout component on the server. + */ + @JsonProperty(value = "agentVersion") + private String agentVersion; + + /** + * The last heartbeat received from the server. + */ + @JsonProperty(value = "lastHeartbeat") + private DateTime lastHeartbeat; + + /** + * Version status. + */ + @JsonProperty(value = "versionStatus") + private String versionStatus; + + /** + * The list of the mobility service updates available on the Process + * Server. + */ + @JsonProperty(value = "mobilityServiceUpdates") + private List mobilityServiceUpdates; + + /** + * The agent generated Id. + */ + @JsonProperty(value = "hostId") + private String hostId; + + /** + * The servers configured with this PS. + */ + @JsonProperty(value = "machineCount") + private String machineCount; + + /** + * The number of replication pairs configured in this PS. + */ + @JsonProperty(value = "replicationPairCount") + private String replicationPairCount; + + /** + * The percentage of the system load. + */ + @JsonProperty(value = "systemLoad") + private String systemLoad; + + /** + * The system load status. + */ + @JsonProperty(value = "systemLoadStatus") + private String systemLoadStatus; + + /** + * The percentage of the CPU load. + */ + @JsonProperty(value = "cpuLoad") + private String cpuLoad; + + /** + * The CPU load status. + */ + @JsonProperty(value = "cpuLoadStatus") + private String cpuLoadStatus; + + /** + * The total memory. + */ + @JsonProperty(value = "totalMemoryInBytes") + private Long totalMemoryInBytes; + + /** + * The available memory. + */ + @JsonProperty(value = "availableMemoryInBytes") + private Long availableMemoryInBytes; + + /** + * The memory usage status. + */ + @JsonProperty(value = "memoryUsageStatus") + private String memoryUsageStatus; + + /** + * The total space. + */ + @JsonProperty(value = "totalSpaceInBytes") + private Long totalSpaceInBytes; + + /** + * The available space. + */ + @JsonProperty(value = "availableSpaceInBytes") + private Long availableSpaceInBytes; + + /** + * The space usage status. + */ + @JsonProperty(value = "spaceUsageStatus") + private String spaceUsageStatus; + + /** + * The PS service status. + */ + @JsonProperty(value = "psServiceStatus") + private String psServiceStatus; + + /** + * The PS SSL cert expiry date. + */ + @JsonProperty(value = "sslCertExpiryDate") + private DateTime sslCertExpiryDate; + + /** + * CS SSL cert expiry date. + */ + @JsonProperty(value = "sslCertExpiryRemainingDays") + private Integer sslCertExpiryRemainingDays; + + /** + * OS Version of the process server. Note: This will get populated if user + * has CS version greater than 9.12.0.0. + */ + @JsonProperty(value = "osVersion") + private String osVersion; + + /** + * Health errors. + */ + @JsonProperty(value = "healthErrors") + private List healthErrors; + + /** + * Agent expiry date. + */ + @JsonProperty(value = "agentExpiryDate") + private DateTime agentExpiryDate; + + /** + * The agent version details. + */ + @JsonProperty(value = "agentVersionDetails") + private VersionDetails agentVersionDetails; + + /** + * Get the Process Server's friendly name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the Process Server's friendly name. + * + * @param friendlyName the friendlyName value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the Process Server Id. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the Process Server Id. + * + * @param id the id value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withId(String id) { + this.id = id; + return this; + } + + /** + * Get the IP address of the server. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the IP address of the server. + * + * @param ipAddress the ipAddress value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the OS type of the server. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the OS type of the server. + * + * @param osType the osType value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get the version of the scout component on the server. + * + * @return the agentVersion value + */ + public String agentVersion() { + return this.agentVersion; + } + + /** + * Set the version of the scout component on the server. + * + * @param agentVersion the agentVersion value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withAgentVersion(String agentVersion) { + this.agentVersion = agentVersion; + return this; + } + + /** + * Get the last heartbeat received from the server. + * + * @return the lastHeartbeat value + */ + public DateTime lastHeartbeat() { + return this.lastHeartbeat; + } + + /** + * Set the last heartbeat received from the server. + * + * @param lastHeartbeat the lastHeartbeat value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withLastHeartbeat(DateTime lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + return this; + } + + /** + * Get version status. + * + * @return the versionStatus value + */ + public String versionStatus() { + return this.versionStatus; + } + + /** + * Set version status. + * + * @param versionStatus the versionStatus value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withVersionStatus(String versionStatus) { + this.versionStatus = versionStatus; + return this; + } + + /** + * Get the list of the mobility service updates available on the Process Server. + * + * @return the mobilityServiceUpdates value + */ + public List mobilityServiceUpdates() { + return this.mobilityServiceUpdates; + } + + /** + * Set the list of the mobility service updates available on the Process Server. + * + * @param mobilityServiceUpdates the mobilityServiceUpdates value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withMobilityServiceUpdates(List mobilityServiceUpdates) { + this.mobilityServiceUpdates = mobilityServiceUpdates; + return this; + } + + /** + * Get the agent generated Id. + * + * @return the hostId value + */ + public String hostId() { + return this.hostId; + } + + /** + * Set the agent generated Id. + * + * @param hostId the hostId value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withHostId(String hostId) { + this.hostId = hostId; + return this; + } + + /** + * Get the servers configured with this PS. + * + * @return the machineCount value + */ + public String machineCount() { + return this.machineCount; + } + + /** + * Set the servers configured with this PS. + * + * @param machineCount the machineCount value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withMachineCount(String machineCount) { + this.machineCount = machineCount; + return this; + } + + /** + * Get the number of replication pairs configured in this PS. + * + * @return the replicationPairCount value + */ + public String replicationPairCount() { + return this.replicationPairCount; + } + + /** + * Set the number of replication pairs configured in this PS. + * + * @param replicationPairCount the replicationPairCount value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withReplicationPairCount(String replicationPairCount) { + this.replicationPairCount = replicationPairCount; + return this; + } + + /** + * Get the percentage of the system load. + * + * @return the systemLoad value + */ + public String systemLoad() { + return this.systemLoad; + } + + /** + * Set the percentage of the system load. + * + * @param systemLoad the systemLoad value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withSystemLoad(String systemLoad) { + this.systemLoad = systemLoad; + return this; + } + + /** + * Get the system load status. + * + * @return the systemLoadStatus value + */ + public String systemLoadStatus() { + return this.systemLoadStatus; + } + + /** + * Set the system load status. + * + * @param systemLoadStatus the systemLoadStatus value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withSystemLoadStatus(String systemLoadStatus) { + this.systemLoadStatus = systemLoadStatus; + return this; + } + + /** + * Get the percentage of the CPU load. + * + * @return the cpuLoad value + */ + public String cpuLoad() { + return this.cpuLoad; + } + + /** + * Set the percentage of the CPU load. + * + * @param cpuLoad the cpuLoad value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withCpuLoad(String cpuLoad) { + this.cpuLoad = cpuLoad; + return this; + } + + /** + * Get the CPU load status. + * + * @return the cpuLoadStatus value + */ + public String cpuLoadStatus() { + return this.cpuLoadStatus; + } + + /** + * Set the CPU load status. + * + * @param cpuLoadStatus the cpuLoadStatus value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withCpuLoadStatus(String cpuLoadStatus) { + this.cpuLoadStatus = cpuLoadStatus; + return this; + } + + /** + * Get the total memory. + * + * @return the totalMemoryInBytes value + */ + public Long totalMemoryInBytes() { + return this.totalMemoryInBytes; + } + + /** + * Set the total memory. + * + * @param totalMemoryInBytes the totalMemoryInBytes value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withTotalMemoryInBytes(Long totalMemoryInBytes) { + this.totalMemoryInBytes = totalMemoryInBytes; + return this; + } + + /** + * Get the available memory. + * + * @return the availableMemoryInBytes value + */ + public Long availableMemoryInBytes() { + return this.availableMemoryInBytes; + } + + /** + * Set the available memory. + * + * @param availableMemoryInBytes the availableMemoryInBytes value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withAvailableMemoryInBytes(Long availableMemoryInBytes) { + this.availableMemoryInBytes = availableMemoryInBytes; + return this; + } + + /** + * Get the memory usage status. + * + * @return the memoryUsageStatus value + */ + public String memoryUsageStatus() { + return this.memoryUsageStatus; + } + + /** + * Set the memory usage status. + * + * @param memoryUsageStatus the memoryUsageStatus value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withMemoryUsageStatus(String memoryUsageStatus) { + this.memoryUsageStatus = memoryUsageStatus; + return this; + } + + /** + * Get the total space. + * + * @return the totalSpaceInBytes value + */ + public Long totalSpaceInBytes() { + return this.totalSpaceInBytes; + } + + /** + * Set the total space. + * + * @param totalSpaceInBytes the totalSpaceInBytes value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withTotalSpaceInBytes(Long totalSpaceInBytes) { + this.totalSpaceInBytes = totalSpaceInBytes; + return this; + } + + /** + * Get the available space. + * + * @return the availableSpaceInBytes value + */ + public Long availableSpaceInBytes() { + return this.availableSpaceInBytes; + } + + /** + * Set the available space. + * + * @param availableSpaceInBytes the availableSpaceInBytes value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withAvailableSpaceInBytes(Long availableSpaceInBytes) { + this.availableSpaceInBytes = availableSpaceInBytes; + return this; + } + + /** + * Get the space usage status. + * + * @return the spaceUsageStatus value + */ + public String spaceUsageStatus() { + return this.spaceUsageStatus; + } + + /** + * Set the space usage status. + * + * @param spaceUsageStatus the spaceUsageStatus value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withSpaceUsageStatus(String spaceUsageStatus) { + this.spaceUsageStatus = spaceUsageStatus; + return this; + } + + /** + * Get the PS service status. + * + * @return the psServiceStatus value + */ + public String psServiceStatus() { + return this.psServiceStatus; + } + + /** + * Set the PS service status. + * + * @param psServiceStatus the psServiceStatus value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withPsServiceStatus(String psServiceStatus) { + this.psServiceStatus = psServiceStatus; + return this; + } + + /** + * Get the PS SSL cert expiry date. + * + * @return the sslCertExpiryDate value + */ + public DateTime sslCertExpiryDate() { + return this.sslCertExpiryDate; + } + + /** + * Set the PS SSL cert expiry date. + * + * @param sslCertExpiryDate the sslCertExpiryDate value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withSslCertExpiryDate(DateTime sslCertExpiryDate) { + this.sslCertExpiryDate = sslCertExpiryDate; + return this; + } + + /** + * Get cS SSL cert expiry date. + * + * @return the sslCertExpiryRemainingDays value + */ + public Integer sslCertExpiryRemainingDays() { + return this.sslCertExpiryRemainingDays; + } + + /** + * Set cS SSL cert expiry date. + * + * @param sslCertExpiryRemainingDays the sslCertExpiryRemainingDays value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withSslCertExpiryRemainingDays(Integer sslCertExpiryRemainingDays) { + this.sslCertExpiryRemainingDays = sslCertExpiryRemainingDays; + return this; + } + + /** + * Get oS Version of the process server. Note: This will get populated if user has CS version greater than 9.12.0.0. + * + * @return the osVersion value + */ + public String osVersion() { + return this.osVersion; + } + + /** + * Set oS Version of the process server. Note: This will get populated if user has CS version greater than 9.12.0.0. + * + * @param osVersion the osVersion value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withOsVersion(String osVersion) { + this.osVersion = osVersion; + return this; + } + + /** + * Get health errors. + * + * @return the healthErrors value + */ + public List healthErrors() { + return this.healthErrors; + } + + /** + * Set health errors. + * + * @param healthErrors the healthErrors value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withHealthErrors(List healthErrors) { + this.healthErrors = healthErrors; + return this; + } + + /** + * Get agent expiry date. + * + * @return the agentExpiryDate value + */ + public DateTime agentExpiryDate() { + return this.agentExpiryDate; + } + + /** + * Set agent expiry date. + * + * @param agentExpiryDate the agentExpiryDate value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withAgentExpiryDate(DateTime agentExpiryDate) { + this.agentExpiryDate = agentExpiryDate; + return this; + } + + /** + * Get the agent version details. + * + * @return the agentVersionDetails value + */ + public VersionDetails agentVersionDetails() { + return this.agentVersionDetails; + } + + /** + * Set the agent version details. + * + * @param agentVersionDetails the agentVersionDetails value to set + * @return the ProcessServer object itself. + */ + public ProcessServer withAgentVersionDetails(VersionDetails agentVersionDetails) { + this.agentVersionDetails = agentVersionDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItem.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItem.java new file mode 100644 index 0000000000000..e80943070106d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItem.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ProtectableItemInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing ProtectableItem. + */ +public interface ProtectableItem extends HasInner, Indexable, Refreshable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + ProtectableItemProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItemProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItemProperties.java new file mode 100644 index 0000000000000..9a21231a31f9c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItemProperties.java @@ -0,0 +1,200 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Replication protected item custom data details. + */ +public class ProtectableItemProperties { + /** + * The name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The protection status. + */ + @JsonProperty(value = "protectionStatus") + private String protectionStatus; + + /** + * The ARM resource of protected items. + */ + @JsonProperty(value = "replicationProtectedItemId") + private String replicationProtectedItemId; + + /** + * The recovery provider ARM Id. + */ + @JsonProperty(value = "recoveryServicesProviderId") + private String recoveryServicesProviderId; + + /** + * The Current protection readiness errors. + */ + @JsonProperty(value = "protectionReadinessErrors") + private List protectionReadinessErrors; + + /** + * The list of replication providers supported for the protectable item. + */ + @JsonProperty(value = "supportedReplicationProviders") + private List supportedReplicationProviders; + + /** + * The Replication provider custom settings. + */ + @JsonProperty(value = "customDetails") + private ConfigurationSettings customDetails; + + /** + * Get the name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the name. + * + * @param friendlyName the friendlyName value to set + * @return the ProtectableItemProperties object itself. + */ + public ProtectableItemProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the protection status. + * + * @return the protectionStatus value + */ + public String protectionStatus() { + return this.protectionStatus; + } + + /** + * Set the protection status. + * + * @param protectionStatus the protectionStatus value to set + * @return the ProtectableItemProperties object itself. + */ + public ProtectableItemProperties withProtectionStatus(String protectionStatus) { + this.protectionStatus = protectionStatus; + return this; + } + + /** + * Get the ARM resource of protected items. + * + * @return the replicationProtectedItemId value + */ + public String replicationProtectedItemId() { + return this.replicationProtectedItemId; + } + + /** + * Set the ARM resource of protected items. + * + * @param replicationProtectedItemId the replicationProtectedItemId value to set + * @return the ProtectableItemProperties object itself. + */ + public ProtectableItemProperties withReplicationProtectedItemId(String replicationProtectedItemId) { + this.replicationProtectedItemId = replicationProtectedItemId; + return this; + } + + /** + * Get the recovery provider ARM Id. + * + * @return the recoveryServicesProviderId value + */ + public String recoveryServicesProviderId() { + return this.recoveryServicesProviderId; + } + + /** + * Set the recovery provider ARM Id. + * + * @param recoveryServicesProviderId the recoveryServicesProviderId value to set + * @return the ProtectableItemProperties object itself. + */ + public ProtectableItemProperties withRecoveryServicesProviderId(String recoveryServicesProviderId) { + this.recoveryServicesProviderId = recoveryServicesProviderId; + return this; + } + + /** + * Get the Current protection readiness errors. + * + * @return the protectionReadinessErrors value + */ + public List protectionReadinessErrors() { + return this.protectionReadinessErrors; + } + + /** + * Set the Current protection readiness errors. + * + * @param protectionReadinessErrors the protectionReadinessErrors value to set + * @return the ProtectableItemProperties object itself. + */ + public ProtectableItemProperties withProtectionReadinessErrors(List protectionReadinessErrors) { + this.protectionReadinessErrors = protectionReadinessErrors; + return this; + } + + /** + * Get the list of replication providers supported for the protectable item. + * + * @return the supportedReplicationProviders value + */ + public List supportedReplicationProviders() { + return this.supportedReplicationProviders; + } + + /** + * Set the list of replication providers supported for the protectable item. + * + * @param supportedReplicationProviders the supportedReplicationProviders value to set + * @return the ProtectableItemProperties object itself. + */ + public ProtectableItemProperties withSupportedReplicationProviders(List supportedReplicationProviders) { + this.supportedReplicationProviders = supportedReplicationProviders; + return this; + } + + /** + * Get the Replication provider custom settings. + * + * @return the customDetails value + */ + public ConfigurationSettings customDetails() { + return this.customDetails; + } + + /** + * Set the Replication provider custom settings. + * + * @param customDetails the customDetails value to set + * @return the ProtectableItemProperties object itself. + */ + public ProtectableItemProperties withCustomDetails(ConfigurationSettings customDetails) { + this.customDetails = customDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItemQueryParameter.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItemQueryParameter.java new file mode 100644 index 0000000000000..147f8b8ad9c24 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectableItemQueryParameter.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Query parameter to enumerate Protectable items. + */ +public class ProtectableItemQueryParameter { + /** + * State of the Protectable item query filter. + */ + @JsonProperty(value = "state") + private String state; + + /** + * Get state of the Protectable item query filter. + * + * @return the state value + */ + public String state() { + return this.state; + } + + /** + * Set state of the Protectable item query filter. + * + * @param state the state value to set + * @return the ProtectableItemQueryParameter object itself. + */ + public ProtectableItemQueryParameter withState(String state) { + this.state = state; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectedItemsQueryParameter.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectedItemsQueryParameter.java new file mode 100644 index 0000000000000..c8530cced01b0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectedItemsQueryParameter.java @@ -0,0 +1,148 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Query parameter to enumerate protected items. + */ +public class ProtectedItemsQueryParameter { + /** + * The source fabric name filter. + */ + @JsonProperty(value = "sourceFabricName") + private String sourceFabricName; + + /** + * The recovery plan filter. + */ + @JsonProperty(value = "recoveryPlanName") + private String recoveryPlanName; + + /** + * The vCenter name filter. + */ + @JsonProperty(value = "vCenterName") + private String vCenterName; + + /** + * The replication provider type. + */ + @JsonProperty(value = "instanceType") + private String instanceType; + + /** + * Whether Multi VM group is auto created or specified by user. Possible + * values include: 'AutoCreated', 'UserSpecified'. + */ + @JsonProperty(value = "multiVmGroupCreateOption") + private MultiVmGroupCreateOption multiVmGroupCreateOption; + + /** + * Get the source fabric name filter. + * + * @return the sourceFabricName value + */ + public String sourceFabricName() { + return this.sourceFabricName; + } + + /** + * Set the source fabric name filter. + * + * @param sourceFabricName the sourceFabricName value to set + * @return the ProtectedItemsQueryParameter object itself. + */ + public ProtectedItemsQueryParameter withSourceFabricName(String sourceFabricName) { + this.sourceFabricName = sourceFabricName; + return this; + } + + /** + * Get the recovery plan filter. + * + * @return the recoveryPlanName value + */ + public String recoveryPlanName() { + return this.recoveryPlanName; + } + + /** + * Set the recovery plan filter. + * + * @param recoveryPlanName the recoveryPlanName value to set + * @return the ProtectedItemsQueryParameter object itself. + */ + public ProtectedItemsQueryParameter withRecoveryPlanName(String recoveryPlanName) { + this.recoveryPlanName = recoveryPlanName; + return this; + } + + /** + * Get the vCenter name filter. + * + * @return the vCenterName value + */ + public String vCenterName() { + return this.vCenterName; + } + + /** + * Set the vCenter name filter. + * + * @param vCenterName the vCenterName value to set + * @return the ProtectedItemsQueryParameter object itself. + */ + public ProtectedItemsQueryParameter withVCenterName(String vCenterName) { + this.vCenterName = vCenterName; + return this; + } + + /** + * Get the replication provider type. + * + * @return the instanceType value + */ + public String instanceType() { + return this.instanceType; + } + + /** + * Set the replication provider type. + * + * @param instanceType the instanceType value to set + * @return the ProtectedItemsQueryParameter object itself. + */ + public ProtectedItemsQueryParameter withInstanceType(String instanceType) { + this.instanceType = instanceType; + return this; + } + + /** + * Get whether Multi VM group is auto created or specified by user. Possible values include: 'AutoCreated', 'UserSpecified'. + * + * @return the multiVmGroupCreateOption value + */ + public MultiVmGroupCreateOption multiVmGroupCreateOption() { + return this.multiVmGroupCreateOption; + } + + /** + * Set whether Multi VM group is auto created or specified by user. Possible values include: 'AutoCreated', 'UserSpecified'. + * + * @param multiVmGroupCreateOption the multiVmGroupCreateOption value to set + * @return the ProtectedItemsQueryParameter object itself. + */ + public ProtectedItemsQueryParameter withMultiVmGroupCreateOption(MultiVmGroupCreateOption multiVmGroupCreateOption) { + this.multiVmGroupCreateOption = multiVmGroupCreateOption; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainer.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainer.java new file mode 100644 index 0000000000000..c9af135010fb6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainer.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ProtectionContainerInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; +import java.util.List; + +/** + * Type representing ProtectionContainer. + */ +public interface ProtectionContainer extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + ProtectionContainerProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the ProtectionContainer definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithReplicationFabric, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of ProtectionContainer definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a ProtectionContainer definition. + */ + interface Blank extends WithReplicationFabric { + } + + /** + * The stage of the protectioncontainer definition allowing to specify ReplicationFabric. + */ + interface WithReplicationFabric { + /** + * Specifies fabricName. + * @param fabricName Unique fabric ARM name + * @return the next definition stage + */ + WithProperties withExistingReplicationFabric(String fabricName); + } + + /** + * The stage of the protectioncontainer definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Create protection container input properties + * @return the next definition stage + */ + WithCreate withProperties(CreateProtectionContainerInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a ProtectionContainer update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of ProtectionContainer update stages. + */ + interface UpdateStages { + /** + * The stage of the protectioncontainer update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Create protection container input properties + * @return the next update stage + */ + Update withProperties(CreateProtectionContainerInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerFabricSpecificDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerFabricSpecificDetails.java new file mode 100644 index 0000000000000..110117d3084f5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerFabricSpecificDetails.java @@ -0,0 +1,32 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Base class for fabric specific details of container. + */ +public class ProtectionContainerFabricSpecificDetails { + /** + * Gets the class type. Overridden in derived classes. + */ + @JsonProperty(value = "instanceType", access = JsonProperty.Access.WRITE_ONLY) + private String instanceType; + + /** + * Get gets the class type. Overridden in derived classes. + * + * @return the instanceType value + */ + public String instanceType() { + return this.instanceType; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMapping.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMapping.java new file mode 100644 index 0000000000000..f34ed3efc632d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMapping.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ProtectionContainerMappingInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing ProtectionContainerMapping. + */ +public interface ProtectionContainerMapping extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + ProtectionContainerMappingProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the ProtectionContainerMapping definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithReplicationProtectionContainer, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of ProtectionContainerMapping definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a ProtectionContainerMapping definition. + */ + interface Blank extends WithReplicationProtectionContainer { + } + + /** + * The stage of the protectioncontainermapping definition allowing to specify ReplicationProtectionContainer. + */ + interface WithReplicationProtectionContainer { + /** + * Specifies fabricName, protectionContainerName. + * @param fabricName Fabric name + * @param protectionContainerName Protection container name + * @return the next definition stage + */ + WithProperties withExistingReplicationProtectionContainer(String fabricName, String protectionContainerName); + } + + /** + * The stage of the protectioncontainermapping definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Configure protection input properties + * @return the next definition stage + */ + WithCreate withProperties(CreateProtectionContainerMappingInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a ProtectionContainerMapping update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of ProtectionContainerMapping update stages. + */ + interface UpdateStages { + /** + * The stage of the protectioncontainermapping update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Update protection container mapping input properties + * @return the next update stage + */ + Update withProperties(UpdateProtectionContainerMappingInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMappingProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMappingProperties.java new file mode 100644 index 0000000000000..fa224d59851f4 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMappingProperties.java @@ -0,0 +1,304 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Protection container mapping properties. + */ +public class ProtectionContainerMappingProperties { + /** + * Paired protection container ARM ID. + */ + @JsonProperty(value = "targetProtectionContainerId") + private String targetProtectionContainerId; + + /** + * Friendly name of paired container. + */ + @JsonProperty(value = "targetProtectionContainerFriendlyName") + private String targetProtectionContainerFriendlyName; + + /** + * Provider specific provider details. + */ + @JsonProperty(value = "providerSpecificDetails") + private ProtectionContainerMappingProviderSpecificDetails providerSpecificDetails; + + /** + * Health of pairing. + */ + @JsonProperty(value = "health") + private String health; + + /** + * Health error. + */ + @JsonProperty(value = "healthErrorDetails") + private List healthErrorDetails; + + /** + * Policy ARM Id. + */ + @JsonProperty(value = "policyId") + private String policyId; + + /** + * Association Status. + */ + @JsonProperty(value = "state") + private String state; + + /** + * Friendly name of source protection container. + */ + @JsonProperty(value = "sourceProtectionContainerFriendlyName") + private String sourceProtectionContainerFriendlyName; + + /** + * Friendly name of source fabric. + */ + @JsonProperty(value = "sourceFabricFriendlyName") + private String sourceFabricFriendlyName; + + /** + * Friendly name of target fabric. + */ + @JsonProperty(value = "targetFabricFriendlyName") + private String targetFabricFriendlyName; + + /** + * Friendly name of replication policy. + */ + @JsonProperty(value = "policyFriendlyName") + private String policyFriendlyName; + + /** + * Get paired protection container ARM ID. + * + * @return the targetProtectionContainerId value + */ + public String targetProtectionContainerId() { + return this.targetProtectionContainerId; + } + + /** + * Set paired protection container ARM ID. + * + * @param targetProtectionContainerId the targetProtectionContainerId value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withTargetProtectionContainerId(String targetProtectionContainerId) { + this.targetProtectionContainerId = targetProtectionContainerId; + return this; + } + + /** + * Get friendly name of paired container. + * + * @return the targetProtectionContainerFriendlyName value + */ + public String targetProtectionContainerFriendlyName() { + return this.targetProtectionContainerFriendlyName; + } + + /** + * Set friendly name of paired container. + * + * @param targetProtectionContainerFriendlyName the targetProtectionContainerFriendlyName value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withTargetProtectionContainerFriendlyName(String targetProtectionContainerFriendlyName) { + this.targetProtectionContainerFriendlyName = targetProtectionContainerFriendlyName; + return this; + } + + /** + * Get provider specific provider details. + * + * @return the providerSpecificDetails value + */ + public ProtectionContainerMappingProviderSpecificDetails providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set provider specific provider details. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withProviderSpecificDetails(ProtectionContainerMappingProviderSpecificDetails providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + + /** + * Get health of pairing. + * + * @return the health value + */ + public String health() { + return this.health; + } + + /** + * Set health of pairing. + * + * @param health the health value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withHealth(String health) { + this.health = health; + return this; + } + + /** + * Get health error. + * + * @return the healthErrorDetails value + */ + public List healthErrorDetails() { + return this.healthErrorDetails; + } + + /** + * Set health error. + * + * @param healthErrorDetails the healthErrorDetails value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withHealthErrorDetails(List healthErrorDetails) { + this.healthErrorDetails = healthErrorDetails; + return this; + } + + /** + * Get policy ARM Id. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Set policy ARM Id. + * + * @param policyId the policyId value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withPolicyId(String policyId) { + this.policyId = policyId; + return this; + } + + /** + * Get association Status. + * + * @return the state value + */ + public String state() { + return this.state; + } + + /** + * Set association Status. + * + * @param state the state value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withState(String state) { + this.state = state; + return this; + } + + /** + * Get friendly name of source protection container. + * + * @return the sourceProtectionContainerFriendlyName value + */ + public String sourceProtectionContainerFriendlyName() { + return this.sourceProtectionContainerFriendlyName; + } + + /** + * Set friendly name of source protection container. + * + * @param sourceProtectionContainerFriendlyName the sourceProtectionContainerFriendlyName value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withSourceProtectionContainerFriendlyName(String sourceProtectionContainerFriendlyName) { + this.sourceProtectionContainerFriendlyName = sourceProtectionContainerFriendlyName; + return this; + } + + /** + * Get friendly name of source fabric. + * + * @return the sourceFabricFriendlyName value + */ + public String sourceFabricFriendlyName() { + return this.sourceFabricFriendlyName; + } + + /** + * Set friendly name of source fabric. + * + * @param sourceFabricFriendlyName the sourceFabricFriendlyName value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withSourceFabricFriendlyName(String sourceFabricFriendlyName) { + this.sourceFabricFriendlyName = sourceFabricFriendlyName; + return this; + } + + /** + * Get friendly name of target fabric. + * + * @return the targetFabricFriendlyName value + */ + public String targetFabricFriendlyName() { + return this.targetFabricFriendlyName; + } + + /** + * Set friendly name of target fabric. + * + * @param targetFabricFriendlyName the targetFabricFriendlyName value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withTargetFabricFriendlyName(String targetFabricFriendlyName) { + this.targetFabricFriendlyName = targetFabricFriendlyName; + return this; + } + + /** + * Get friendly name of replication policy. + * + * @return the policyFriendlyName value + */ + public String policyFriendlyName() { + return this.policyFriendlyName; + } + + /** + * Set friendly name of replication policy. + * + * @param policyFriendlyName the policyFriendlyName value to set + * @return the ProtectionContainerMappingProperties object itself. + */ + public ProtectionContainerMappingProperties withPolicyFriendlyName(String policyFriendlyName) { + this.policyFriendlyName = policyFriendlyName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMappingProviderSpecificDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMappingProviderSpecificDetails.java new file mode 100644 index 0000000000000..aa656290e2430 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerMappingProviderSpecificDetails.java @@ -0,0 +1,25 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Container mapping provider specific details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ProtectionContainerMappingProviderSpecificDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AProtectionContainerMappingDetails.class), + @JsonSubTypes.Type(name = "VMwareCbt", value = VMwareCbtProtectionContainerMappingDetails.class) +}) +public class ProtectionContainerMappingProviderSpecificDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerProperties.java new file mode 100644 index 0000000000000..d993137e598c7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProtectionContainerProperties.java @@ -0,0 +1,199 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Protection profile custom data details. + */ +public class ProtectionContainerProperties { + /** + * Fabric friendly name. + */ + @JsonProperty(value = "fabricFriendlyName") + private String fabricFriendlyName; + + /** + * The name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The fabric type. + */ + @JsonProperty(value = "fabricType") + private String fabricType; + + /** + * Number of protected PEs. + */ + @JsonProperty(value = "protectedItemCount") + private Integer protectedItemCount; + + /** + * The pairing status of this cloud. + */ + @JsonProperty(value = "pairingStatus") + private String pairingStatus; + + /** + * The role of this cloud. + */ + @JsonProperty(value = "role") + private String role; + + /** + * Fabric specific details. + */ + @JsonProperty(value = "fabricSpecificDetails") + private ProtectionContainerFabricSpecificDetails fabricSpecificDetails; + + /** + * Get fabric friendly name. + * + * @return the fabricFriendlyName value + */ + public String fabricFriendlyName() { + return this.fabricFriendlyName; + } + + /** + * Set fabric friendly name. + * + * @param fabricFriendlyName the fabricFriendlyName value to set + * @return the ProtectionContainerProperties object itself. + */ + public ProtectionContainerProperties withFabricFriendlyName(String fabricFriendlyName) { + this.fabricFriendlyName = fabricFriendlyName; + return this; + } + + /** + * Get the name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the name. + * + * @param friendlyName the friendlyName value to set + * @return the ProtectionContainerProperties object itself. + */ + public ProtectionContainerProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the fabric type. + * + * @return the fabricType value + */ + public String fabricType() { + return this.fabricType; + } + + /** + * Set the fabric type. + * + * @param fabricType the fabricType value to set + * @return the ProtectionContainerProperties object itself. + */ + public ProtectionContainerProperties withFabricType(String fabricType) { + this.fabricType = fabricType; + return this; + } + + /** + * Get number of protected PEs. + * + * @return the protectedItemCount value + */ + public Integer protectedItemCount() { + return this.protectedItemCount; + } + + /** + * Set number of protected PEs. + * + * @param protectedItemCount the protectedItemCount value to set + * @return the ProtectionContainerProperties object itself. + */ + public ProtectionContainerProperties withProtectedItemCount(Integer protectedItemCount) { + this.protectedItemCount = protectedItemCount; + return this; + } + + /** + * Get the pairing status of this cloud. + * + * @return the pairingStatus value + */ + public String pairingStatus() { + return this.pairingStatus; + } + + /** + * Set the pairing status of this cloud. + * + * @param pairingStatus the pairingStatus value to set + * @return the ProtectionContainerProperties object itself. + */ + public ProtectionContainerProperties withPairingStatus(String pairingStatus) { + this.pairingStatus = pairingStatus; + return this; + } + + /** + * Get the role of this cloud. + * + * @return the role value + */ + public String role() { + return this.role; + } + + /** + * Set the role of this cloud. + * + * @param role the role value to set + * @return the ProtectionContainerProperties object itself. + */ + public ProtectionContainerProperties withRole(String role) { + this.role = role; + return this; + } + + /** + * Get fabric specific details. + * + * @return the fabricSpecificDetails value + */ + public ProtectionContainerFabricSpecificDetails fabricSpecificDetails() { + return this.fabricSpecificDetails; + } + + /** + * Set fabric specific details. + * + * @param fabricSpecificDetails the fabricSpecificDetails value to set + * @return the ProtectionContainerProperties object itself. + */ + public ProtectionContainerProperties withFabricSpecificDetails(ProtectionContainerFabricSpecificDetails fabricSpecificDetails) { + this.fabricSpecificDetails = fabricSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderError.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderError.java new file mode 100644 index 0000000000000..26ad3a4c99a7e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderError.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * This class contains the error details per object. + */ +public class ProviderError { + /** + * The Error code. + */ + @JsonProperty(value = "errorCode") + private Integer errorCode; + + /** + * The Error message. + */ + @JsonProperty(value = "errorMessage") + private String errorMessage; + + /** + * The Provider error Id. + */ + @JsonProperty(value = "errorId") + private String errorId; + + /** + * The possible causes for the error. + */ + @JsonProperty(value = "possibleCauses") + private String possibleCauses; + + /** + * The recommended action to resolve the error. + */ + @JsonProperty(value = "recommendedAction") + private String recommendedAction; + + /** + * Get the Error code. + * + * @return the errorCode value + */ + public Integer errorCode() { + return this.errorCode; + } + + /** + * Set the Error code. + * + * @param errorCode the errorCode value to set + * @return the ProviderError object itself. + */ + public ProviderError withErrorCode(Integer errorCode) { + this.errorCode = errorCode; + return this; + } + + /** + * Get the Error message. + * + * @return the errorMessage value + */ + public String errorMessage() { + return this.errorMessage; + } + + /** + * Set the Error message. + * + * @param errorMessage the errorMessage value to set + * @return the ProviderError object itself. + */ + public ProviderError withErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + /** + * Get the Provider error Id. + * + * @return the errorId value + */ + public String errorId() { + return this.errorId; + } + + /** + * Set the Provider error Id. + * + * @param errorId the errorId value to set + * @return the ProviderError object itself. + */ + public ProviderError withErrorId(String errorId) { + this.errorId = errorId; + return this; + } + + /** + * Get the possible causes for the error. + * + * @return the possibleCauses value + */ + public String possibleCauses() { + return this.possibleCauses; + } + + /** + * Set the possible causes for the error. + * + * @param possibleCauses the possibleCauses value to set + * @return the ProviderError object itself. + */ + public ProviderError withPossibleCauses(String possibleCauses) { + this.possibleCauses = possibleCauses; + return this; + } + + /** + * Get the recommended action to resolve the error. + * + * @return the recommendedAction value + */ + public String recommendedAction() { + return this.recommendedAction; + } + + /** + * Set the recommended action to resolve the error. + * + * @param recommendedAction the recommendedAction value to set + * @return the ProviderError object itself. + */ + public ProviderError withRecommendedAction(String recommendedAction) { + this.recommendedAction = recommendedAction; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderSpecificFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderSpecificFailoverInput.java new file mode 100644 index 0000000000000..1bab9c6da96e1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderSpecificFailoverInput.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Provider specific failover input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ProviderSpecificFailoverInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AFailoverProviderInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzureFailback", value = HyperVReplicaAzureFailbackProviderInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzureFailoverProviderInput.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2FailoverProviderInput.class), + @JsonSubTypes.Type(name = "InMage", value = InMageFailoverProviderInput.class) +}) +public class ProviderSpecificFailoverInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderSpecificRecoveryPointDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderSpecificRecoveryPointDetails.java new file mode 100644 index 0000000000000..b6c68586010ee --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ProviderSpecificRecoveryPointDetails.java @@ -0,0 +1,25 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Replication provider specific recovery point details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ProviderSpecificRecoveryPointDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2ARecoveryPointDetails.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2RecoveryPointDetails.class) +}) +public class ProviderSpecificRecoveryPointDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RcmAzureMigrationPolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RcmAzureMigrationPolicyDetails.java new file mode 100644 index 0000000000000..7b3679329c5ff --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RcmAzureMigrationPolicyDetails.java @@ -0,0 +1,153 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * RCM based Azure migration specific policy details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("RcmAzureMigration") +public class RcmAzureMigrationPolicyDetails extends PolicyProviderSpecificDetails { + /** + * The recovery point threshold in minutes. + */ + @JsonProperty(value = "recoveryPointThresholdInMinutes") + private Integer recoveryPointThresholdInMinutes; + + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistory") + private Integer recoveryPointHistory; + + /** + * The app consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * A value indicating whether multi-VM sync has to be enabled. Possible + * values include: 'Enabled', 'Disabled'. + */ + @JsonProperty(value = "multiVmSyncStatus") + private MultiVmSyncStatus multiVmSyncStatus; + + /** + * The crash consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "crashConsistentFrequencyInMinutes") + private Integer crashConsistentFrequencyInMinutes; + + /** + * Get the recovery point threshold in minutes. + * + * @return the recoveryPointThresholdInMinutes value + */ + public Integer recoveryPointThresholdInMinutes() { + return this.recoveryPointThresholdInMinutes; + } + + /** + * Set the recovery point threshold in minutes. + * + * @param recoveryPointThresholdInMinutes the recoveryPointThresholdInMinutes value to set + * @return the RcmAzureMigrationPolicyDetails object itself. + */ + public RcmAzureMigrationPolicyDetails withRecoveryPointThresholdInMinutes(Integer recoveryPointThresholdInMinutes) { + this.recoveryPointThresholdInMinutes = recoveryPointThresholdInMinutes; + return this; + } + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistory value + */ + public Integer recoveryPointHistory() { + return this.recoveryPointHistory; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistory the recoveryPointHistory value to set + * @return the RcmAzureMigrationPolicyDetails object itself. + */ + public RcmAzureMigrationPolicyDetails withRecoveryPointHistory(Integer recoveryPointHistory) { + this.recoveryPointHistory = recoveryPointHistory; + return this; + } + + /** + * Get the app consistent snapshot frequency in minutes. + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency in minutes. + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the RcmAzureMigrationPolicyDetails object itself. + */ + public RcmAzureMigrationPolicyDetails withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get a value indicating whether multi-VM sync has to be enabled. Possible values include: 'Enabled', 'Disabled'. + * + * @return the multiVmSyncStatus value + */ + public MultiVmSyncStatus multiVmSyncStatus() { + return this.multiVmSyncStatus; + } + + /** + * Set a value indicating whether multi-VM sync has to be enabled. Possible values include: 'Enabled', 'Disabled'. + * + * @param multiVmSyncStatus the multiVmSyncStatus value to set + * @return the RcmAzureMigrationPolicyDetails object itself. + */ + public RcmAzureMigrationPolicyDetails withMultiVmSyncStatus(MultiVmSyncStatus multiVmSyncStatus) { + this.multiVmSyncStatus = multiVmSyncStatus; + return this; + } + + /** + * Get the crash consistent snapshot frequency in minutes. + * + * @return the crashConsistentFrequencyInMinutes value + */ + public Integer crashConsistentFrequencyInMinutes() { + return this.crashConsistentFrequencyInMinutes; + } + + /** + * Set the crash consistent snapshot frequency in minutes. + * + * @param crashConsistentFrequencyInMinutes the crashConsistentFrequencyInMinutes value to set + * @return the RcmAzureMigrationPolicyDetails object itself. + */ + public RcmAzureMigrationPolicyDetails withCrashConsistentFrequencyInMinutes(Integer crashConsistentFrequencyInMinutes) { + this.crashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlan.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlan.java new file mode 100644 index 0000000000000..a8beee0353b78 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlan.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryPlanInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; +import java.util.List; + +/** + * Type representing RecoveryPlan. + */ +public interface RecoveryPlan extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + RecoveryPlanProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the RecoveryPlan definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithVault, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of RecoveryPlan definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a RecoveryPlan definition. + */ + interface Blank extends WithVault { + } + + /** + * The stage of the recoveryplan definition allowing to specify Vault. + */ + interface WithVault { + /** + * Specifies . + * @return the next definition stage + */ + WithProperties withExistingVault(); + } + + /** + * The stage of the recoveryplan definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Recovery plan creation properties + * @return the next definition stage + */ + WithCreate withProperties(CreateRecoveryPlanInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a RecoveryPlan update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of RecoveryPlan update stages. + */ + interface UpdateStages { + /** + * The stage of the recoveryplan update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Recovery plan update properties + * @return the next update stage + */ + Update withProperties(UpdateRecoveryPlanInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanA2AFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanA2AFailoverInput.java new file mode 100644 index 0000000000000..9d5d2fbca2c1b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanA2AFailoverInput.java @@ -0,0 +1,103 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Recovery plan A2A failover input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("A2A") +public class RecoveryPlanA2AFailoverInput extends RecoveryPlanProviderSpecificFailoverInput { + /** + * The recovery point type. Possible values include: 'Latest', + * 'LatestApplicationConsistent', 'LatestCrashConsistent', + * 'LatestProcessed'. + */ + @JsonProperty(value = "recoveryPointType", required = true) + private A2ARpRecoveryPointType recoveryPointType; + + /** + * A value indicating whether to use recovery cloud service for TFO or not. + */ + @JsonProperty(value = "cloudServiceCreationOption") + private String cloudServiceCreationOption; + + /** + * A value indicating whether multi VM sync enabled VMs should use multi VM + * sync points for failover. Possible values include: + * 'UseMultiVmSyncRecoveryPoint', 'UsePerVmRecoveryPoint'. + */ + @JsonProperty(value = "multiVmSyncPointOption") + private MultiVmSyncPointOption multiVmSyncPointOption; + + /** + * Get the recovery point type. Possible values include: 'Latest', 'LatestApplicationConsistent', 'LatestCrashConsistent', 'LatestProcessed'. + * + * @return the recoveryPointType value + */ + public A2ARpRecoveryPointType recoveryPointType() { + return this.recoveryPointType; + } + + /** + * Set the recovery point type. Possible values include: 'Latest', 'LatestApplicationConsistent', 'LatestCrashConsistent', 'LatestProcessed'. + * + * @param recoveryPointType the recoveryPointType value to set + * @return the RecoveryPlanA2AFailoverInput object itself. + */ + public RecoveryPlanA2AFailoverInput withRecoveryPointType(A2ARpRecoveryPointType recoveryPointType) { + this.recoveryPointType = recoveryPointType; + return this; + } + + /** + * Get a value indicating whether to use recovery cloud service for TFO or not. + * + * @return the cloudServiceCreationOption value + */ + public String cloudServiceCreationOption() { + return this.cloudServiceCreationOption; + } + + /** + * Set a value indicating whether to use recovery cloud service for TFO or not. + * + * @param cloudServiceCreationOption the cloudServiceCreationOption value to set + * @return the RecoveryPlanA2AFailoverInput object itself. + */ + public RecoveryPlanA2AFailoverInput withCloudServiceCreationOption(String cloudServiceCreationOption) { + this.cloudServiceCreationOption = cloudServiceCreationOption; + return this; + } + + /** + * Get a value indicating whether multi VM sync enabled VMs should use multi VM sync points for failover. Possible values include: 'UseMultiVmSyncRecoveryPoint', 'UsePerVmRecoveryPoint'. + * + * @return the multiVmSyncPointOption value + */ + public MultiVmSyncPointOption multiVmSyncPointOption() { + return this.multiVmSyncPointOption; + } + + /** + * Set a value indicating whether multi VM sync enabled VMs should use multi VM sync points for failover. Possible values include: 'UseMultiVmSyncRecoveryPoint', 'UsePerVmRecoveryPoint'. + * + * @param multiVmSyncPointOption the multiVmSyncPointOption value to set + * @return the RecoveryPlanA2AFailoverInput object itself. + */ + public RecoveryPlanA2AFailoverInput withMultiVmSyncPointOption(MultiVmSyncPointOption multiVmSyncPointOption) { + this.multiVmSyncPointOption = multiVmSyncPointOption; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanAction.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanAction.java new file mode 100644 index 0000000000000..ccf663c3bd6fc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanAction.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan action details. + */ +public class RecoveryPlanAction { + /** + * The action name. + */ + @JsonProperty(value = "actionName", required = true) + private String actionName; + + /** + * The list of failover types. + */ + @JsonProperty(value = "failoverTypes", required = true) + private List failoverTypes; + + /** + * The list of failover directions. + */ + @JsonProperty(value = "failoverDirections", required = true) + private List failoverDirections; + + /** + * The custom details. + */ + @JsonProperty(value = "customDetails", required = true) + private RecoveryPlanActionDetails customDetails; + + /** + * Get the action name. + * + * @return the actionName value + */ + public String actionName() { + return this.actionName; + } + + /** + * Set the action name. + * + * @param actionName the actionName value to set + * @return the RecoveryPlanAction object itself. + */ + public RecoveryPlanAction withActionName(String actionName) { + this.actionName = actionName; + return this; + } + + /** + * Get the list of failover types. + * + * @return the failoverTypes value + */ + public List failoverTypes() { + return this.failoverTypes; + } + + /** + * Set the list of failover types. + * + * @param failoverTypes the failoverTypes value to set + * @return the RecoveryPlanAction object itself. + */ + public RecoveryPlanAction withFailoverTypes(List failoverTypes) { + this.failoverTypes = failoverTypes; + return this; + } + + /** + * Get the list of failover directions. + * + * @return the failoverDirections value + */ + public List failoverDirections() { + return this.failoverDirections; + } + + /** + * Set the list of failover directions. + * + * @param failoverDirections the failoverDirections value to set + * @return the RecoveryPlanAction object itself. + */ + public RecoveryPlanAction withFailoverDirections(List failoverDirections) { + this.failoverDirections = failoverDirections; + return this; + } + + /** + * Get the custom details. + * + * @return the customDetails value + */ + public RecoveryPlanActionDetails customDetails() { + return this.customDetails; + } + + /** + * Set the custom details. + * + * @param customDetails the customDetails value to set + * @return the RecoveryPlanAction object itself. + */ + public RecoveryPlanAction withCustomDetails(RecoveryPlanActionDetails customDetails) { + this.customDetails = customDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanActionDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanActionDetails.java new file mode 100644 index 0000000000000..8aeb31b47f924 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanActionDetails.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Recovery plan action custom details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("RecoveryPlanActionDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "AutomationRunbookActionDetails", value = RecoveryPlanAutomationRunbookActionDetails.class), + @JsonSubTypes.Type(name = "ManualActionDetails", value = RecoveryPlanManualActionDetails.class), + @JsonSubTypes.Type(name = "ScriptActionDetails", value = RecoveryPlanScriptActionDetails.class) +}) +public class RecoveryPlanActionDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanActionLocation.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanActionLocation.java new file mode 100644 index 0000000000000..a330d7b4461d2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanActionLocation.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for RecoveryPlanActionLocation. + */ +public final class RecoveryPlanActionLocation extends ExpandableStringEnum { + /** Static value Primary for RecoveryPlanActionLocation. */ + public static final RecoveryPlanActionLocation PRIMARY = fromString("Primary"); + + /** Static value Recovery for RecoveryPlanActionLocation. */ + public static final RecoveryPlanActionLocation RECOVERY = fromString("Recovery"); + + /** + * Creates or finds a RecoveryPlanActionLocation from its string representation. + * @param name a name to look for + * @return the corresponding RecoveryPlanActionLocation + */ + @JsonCreator + public static RecoveryPlanActionLocation fromString(String name) { + return fromString(name, RecoveryPlanActionLocation.class); + } + + /** + * @return known RecoveryPlanActionLocation values + */ + public static Collection values() { + return values(RecoveryPlanActionLocation.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanAutomationRunbookActionDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanAutomationRunbookActionDetails.java new file mode 100644 index 0000000000000..710b75daaf55f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanAutomationRunbookActionDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Recovery plan Automation runbook action details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("AutomationRunbookActionDetails") +public class RecoveryPlanAutomationRunbookActionDetails extends RecoveryPlanActionDetails { + /** + * The runbook ARM Id. + */ + @JsonProperty(value = "runbookId") + private String runbookId; + + /** + * The runbook timeout. + */ + @JsonProperty(value = "timeout") + private String timeout; + + /** + * The fabric location. Possible values include: 'Primary', 'Recovery'. + */ + @JsonProperty(value = "fabricLocation", required = true) + private RecoveryPlanActionLocation fabricLocation; + + /** + * Get the runbook ARM Id. + * + * @return the runbookId value + */ + public String runbookId() { + return this.runbookId; + } + + /** + * Set the runbook ARM Id. + * + * @param runbookId the runbookId value to set + * @return the RecoveryPlanAutomationRunbookActionDetails object itself. + */ + public RecoveryPlanAutomationRunbookActionDetails withRunbookId(String runbookId) { + this.runbookId = runbookId; + return this; + } + + /** + * Get the runbook timeout. + * + * @return the timeout value + */ + public String timeout() { + return this.timeout; + } + + /** + * Set the runbook timeout. + * + * @param timeout the timeout value to set + * @return the RecoveryPlanAutomationRunbookActionDetails object itself. + */ + public RecoveryPlanAutomationRunbookActionDetails withTimeout(String timeout) { + this.timeout = timeout; + return this; + } + + /** + * Get the fabric location. Possible values include: 'Primary', 'Recovery'. + * + * @return the fabricLocation value + */ + public RecoveryPlanActionLocation fabricLocation() { + return this.fabricLocation; + } + + /** + * Set the fabric location. Possible values include: 'Primary', 'Recovery'. + * + * @param fabricLocation the fabricLocation value to set + * @return the RecoveryPlanAutomationRunbookActionDetails object itself. + */ + public RecoveryPlanAutomationRunbookActionDetails withFabricLocation(RecoveryPlanActionLocation fabricLocation) { + this.fabricLocation = fabricLocation; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroup.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroup.java new file mode 100644 index 0000000000000..a43b3384e13cf --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroup.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan group details. + */ +public class RecoveryPlanGroup { + /** + * The group type. Possible values include: 'Shutdown', 'Boot', 'Failover'. + */ + @JsonProperty(value = "groupType", required = true) + private RecoveryPlanGroupType groupType; + + /** + * The list of protected items. + */ + @JsonProperty(value = "replicationProtectedItems") + private List replicationProtectedItems; + + /** + * The start group actions. + */ + @JsonProperty(value = "startGroupActions") + private List startGroupActions; + + /** + * The end group actions. + */ + @JsonProperty(value = "endGroupActions") + private List endGroupActions; + + /** + * Get the group type. Possible values include: 'Shutdown', 'Boot', 'Failover'. + * + * @return the groupType value + */ + public RecoveryPlanGroupType groupType() { + return this.groupType; + } + + /** + * Set the group type. Possible values include: 'Shutdown', 'Boot', 'Failover'. + * + * @param groupType the groupType value to set + * @return the RecoveryPlanGroup object itself. + */ + public RecoveryPlanGroup withGroupType(RecoveryPlanGroupType groupType) { + this.groupType = groupType; + return this; + } + + /** + * Get the list of protected items. + * + * @return the replicationProtectedItems value + */ + public List replicationProtectedItems() { + return this.replicationProtectedItems; + } + + /** + * Set the list of protected items. + * + * @param replicationProtectedItems the replicationProtectedItems value to set + * @return the RecoveryPlanGroup object itself. + */ + public RecoveryPlanGroup withReplicationProtectedItems(List replicationProtectedItems) { + this.replicationProtectedItems = replicationProtectedItems; + return this; + } + + /** + * Get the start group actions. + * + * @return the startGroupActions value + */ + public List startGroupActions() { + return this.startGroupActions; + } + + /** + * Set the start group actions. + * + * @param startGroupActions the startGroupActions value to set + * @return the RecoveryPlanGroup object itself. + */ + public RecoveryPlanGroup withStartGroupActions(List startGroupActions) { + this.startGroupActions = startGroupActions; + return this; + } + + /** + * Get the end group actions. + * + * @return the endGroupActions value + */ + public List endGroupActions() { + return this.endGroupActions; + } + + /** + * Set the end group actions. + * + * @param endGroupActions the endGroupActions value to set + * @return the RecoveryPlanGroup object itself. + */ + public RecoveryPlanGroup withEndGroupActions(List endGroupActions) { + this.endGroupActions = endGroupActions; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroupTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroupTaskDetails.java new file mode 100644 index 0000000000000..12a2da1362671 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroupTaskDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the recovery plan group task. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("RecoveryPlanGroupTaskDetails") +public class RecoveryPlanGroupTaskDetails extends GroupTaskDetails { + /** + * The name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The group identifier. + */ + @JsonProperty(value = "groupId") + private String groupId; + + /** + * The group type. + */ + @JsonProperty(value = "rpGroupType") + private String rpGroupType; + + /** + * Get the name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name. + * + * @param name the name value to set + * @return the RecoveryPlanGroupTaskDetails object itself. + */ + public RecoveryPlanGroupTaskDetails withName(String name) { + this.name = name; + return this; + } + + /** + * Get the group identifier. + * + * @return the groupId value + */ + public String groupId() { + return this.groupId; + } + + /** + * Set the group identifier. + * + * @param groupId the groupId value to set + * @return the RecoveryPlanGroupTaskDetails object itself. + */ + public RecoveryPlanGroupTaskDetails withGroupId(String groupId) { + this.groupId = groupId; + return this; + } + + /** + * Get the group type. + * + * @return the rpGroupType value + */ + public String rpGroupType() { + return this.rpGroupType; + } + + /** + * Set the group type. + * + * @param rpGroupType the rpGroupType value to set + * @return the RecoveryPlanGroupTaskDetails object itself. + */ + public RecoveryPlanGroupTaskDetails withRpGroupType(String rpGroupType) { + this.rpGroupType = rpGroupType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroupType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroupType.java new file mode 100644 index 0000000000000..b60bb398d8bc5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanGroupType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for RecoveryPlanGroupType. + */ +public final class RecoveryPlanGroupType extends ExpandableStringEnum { + /** Static value Shutdown for RecoveryPlanGroupType. */ + public static final RecoveryPlanGroupType SHUTDOWN = fromString("Shutdown"); + + /** Static value Boot for RecoveryPlanGroupType. */ + public static final RecoveryPlanGroupType BOOT = fromString("Boot"); + + /** Static value Failover for RecoveryPlanGroupType. */ + public static final RecoveryPlanGroupType FAILOVER = fromString("Failover"); + + /** + * Creates or finds a RecoveryPlanGroupType from its string representation. + * @param name a name to look for + * @return the corresponding RecoveryPlanGroupType + */ + @JsonCreator + public static RecoveryPlanGroupType fromString(String name) { + return fromString(name, RecoveryPlanGroupType.class); + } + + /** + * @return known RecoveryPlanGroupType values + */ + public static Collection values() { + return values(RecoveryPlanGroupType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanHyperVReplicaAzureFailbackInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanHyperVReplicaAzureFailbackInput.java new file mode 100644 index 0000000000000..c7785424e1823 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanHyperVReplicaAzureFailbackInput.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Recovery plan HVR Azure failback input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzureFailback") +public class RecoveryPlanHyperVReplicaAzureFailbackInput extends RecoveryPlanProviderSpecificFailoverInput { + /** + * The data sync option. Possible values include: 'ForDownTime', + * 'ForSynchronization'. + */ + @JsonProperty(value = "dataSyncOption", required = true) + private DataSyncStatus dataSyncOption; + + /** + * The ALR option. Possible values include: 'CreateVmIfNotFound', + * 'NoAction'. + */ + @JsonProperty(value = "recoveryVmCreationOption", required = true) + private AlternateLocationRecoveryOption recoveryVmCreationOption; + + /** + * Get the data sync option. Possible values include: 'ForDownTime', 'ForSynchronization'. + * + * @return the dataSyncOption value + */ + public DataSyncStatus dataSyncOption() { + return this.dataSyncOption; + } + + /** + * Set the data sync option. Possible values include: 'ForDownTime', 'ForSynchronization'. + * + * @param dataSyncOption the dataSyncOption value to set + * @return the RecoveryPlanHyperVReplicaAzureFailbackInput object itself. + */ + public RecoveryPlanHyperVReplicaAzureFailbackInput withDataSyncOption(DataSyncStatus dataSyncOption) { + this.dataSyncOption = dataSyncOption; + return this; + } + + /** + * Get the ALR option. Possible values include: 'CreateVmIfNotFound', 'NoAction'. + * + * @return the recoveryVmCreationOption value + */ + public AlternateLocationRecoveryOption recoveryVmCreationOption() { + return this.recoveryVmCreationOption; + } + + /** + * Set the ALR option. Possible values include: 'CreateVmIfNotFound', 'NoAction'. + * + * @param recoveryVmCreationOption the recoveryVmCreationOption value to set + * @return the RecoveryPlanHyperVReplicaAzureFailbackInput object itself. + */ + public RecoveryPlanHyperVReplicaAzureFailbackInput withRecoveryVmCreationOption(AlternateLocationRecoveryOption recoveryVmCreationOption) { + this.recoveryVmCreationOption = recoveryVmCreationOption; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanHyperVReplicaAzureFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanHyperVReplicaAzureFailoverInput.java new file mode 100644 index 0000000000000..8b5b393f67598 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanHyperVReplicaAzureFailoverInput.java @@ -0,0 +1,126 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Recovery plan HVR Azure failover input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("HyperVReplicaAzure") +public class RecoveryPlanHyperVReplicaAzureFailoverInput extends RecoveryPlanProviderSpecificFailoverInput { + /** + * The vault location. + */ + @JsonProperty(value = "vaultLocation", required = true) + private String vaultLocation; + + /** + * The primary KEK certificate PFX. + */ + @JsonProperty(value = "primaryKekCertificatePfx") + private String primaryKekCertificatePfx; + + /** + * The secondary KEK certificate PFX. + */ + @JsonProperty(value = "secondaryKekCertificatePfx") + private String secondaryKekCertificatePfx; + + /** + * The recovery point type. Possible values include: 'Latest', + * 'LatestApplicationConsistent', 'LatestProcessed'. + */ + @JsonProperty(value = "recoveryPointType") + private HyperVReplicaAzureRpRecoveryPointType recoveryPointType; + + /** + * Get the vault location. + * + * @return the vaultLocation value + */ + public String vaultLocation() { + return this.vaultLocation; + } + + /** + * Set the vault location. + * + * @param vaultLocation the vaultLocation value to set + * @return the RecoveryPlanHyperVReplicaAzureFailoverInput object itself. + */ + public RecoveryPlanHyperVReplicaAzureFailoverInput withVaultLocation(String vaultLocation) { + this.vaultLocation = vaultLocation; + return this; + } + + /** + * Get the primary KEK certificate PFX. + * + * @return the primaryKekCertificatePfx value + */ + public String primaryKekCertificatePfx() { + return this.primaryKekCertificatePfx; + } + + /** + * Set the primary KEK certificate PFX. + * + * @param primaryKekCertificatePfx the primaryKekCertificatePfx value to set + * @return the RecoveryPlanHyperVReplicaAzureFailoverInput object itself. + */ + public RecoveryPlanHyperVReplicaAzureFailoverInput withPrimaryKekCertificatePfx(String primaryKekCertificatePfx) { + this.primaryKekCertificatePfx = primaryKekCertificatePfx; + return this; + } + + /** + * Get the secondary KEK certificate PFX. + * + * @return the secondaryKekCertificatePfx value + */ + public String secondaryKekCertificatePfx() { + return this.secondaryKekCertificatePfx; + } + + /** + * Set the secondary KEK certificate PFX. + * + * @param secondaryKekCertificatePfx the secondaryKekCertificatePfx value to set + * @return the RecoveryPlanHyperVReplicaAzureFailoverInput object itself. + */ + public RecoveryPlanHyperVReplicaAzureFailoverInput withSecondaryKekCertificatePfx(String secondaryKekCertificatePfx) { + this.secondaryKekCertificatePfx = secondaryKekCertificatePfx; + return this; + } + + /** + * Get the recovery point type. Possible values include: 'Latest', 'LatestApplicationConsistent', 'LatestProcessed'. + * + * @return the recoveryPointType value + */ + public HyperVReplicaAzureRpRecoveryPointType recoveryPointType() { + return this.recoveryPointType; + } + + /** + * Set the recovery point type. Possible values include: 'Latest', 'LatestApplicationConsistent', 'LatestProcessed'. + * + * @param recoveryPointType the recoveryPointType value to set + * @return the RecoveryPlanHyperVReplicaAzureFailoverInput object itself. + */ + public RecoveryPlanHyperVReplicaAzureFailoverInput withRecoveryPointType(HyperVReplicaAzureRpRecoveryPointType recoveryPointType) { + this.recoveryPointType = recoveryPointType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanInMageAzureV2FailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanInMageAzureV2FailoverInput.java new file mode 100644 index 0000000000000..43a13065e1a7a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanInMageAzureV2FailoverInput.java @@ -0,0 +1,102 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Recovery plan InMageAzureV2 failover input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMageAzureV2") +public class RecoveryPlanInMageAzureV2FailoverInput extends RecoveryPlanProviderSpecificFailoverInput { + /** + * The vault location. + */ + @JsonProperty(value = "vaultLocation", required = true) + private String vaultLocation; + + /** + * The recovery point type. Possible values include: 'Latest', + * 'LatestApplicationConsistent', 'LatestCrashConsistent', + * 'LatestProcessed'. + */ + @JsonProperty(value = "recoveryPointType", required = true) + private InMageV2RpRecoveryPointType recoveryPointType; + + /** + * A value indicating whether multi VM sync enabled VMs should use multi VM + * sync points for failover. + */ + @JsonProperty(value = "useMultiVmSyncPoint") + private String useMultiVmSyncPoint; + + /** + * Get the vault location. + * + * @return the vaultLocation value + */ + public String vaultLocation() { + return this.vaultLocation; + } + + /** + * Set the vault location. + * + * @param vaultLocation the vaultLocation value to set + * @return the RecoveryPlanInMageAzureV2FailoverInput object itself. + */ + public RecoveryPlanInMageAzureV2FailoverInput withVaultLocation(String vaultLocation) { + this.vaultLocation = vaultLocation; + return this; + } + + /** + * Get the recovery point type. Possible values include: 'Latest', 'LatestApplicationConsistent', 'LatestCrashConsistent', 'LatestProcessed'. + * + * @return the recoveryPointType value + */ + public InMageV2RpRecoveryPointType recoveryPointType() { + return this.recoveryPointType; + } + + /** + * Set the recovery point type. Possible values include: 'Latest', 'LatestApplicationConsistent', 'LatestCrashConsistent', 'LatestProcessed'. + * + * @param recoveryPointType the recoveryPointType value to set + * @return the RecoveryPlanInMageAzureV2FailoverInput object itself. + */ + public RecoveryPlanInMageAzureV2FailoverInput withRecoveryPointType(InMageV2RpRecoveryPointType recoveryPointType) { + this.recoveryPointType = recoveryPointType; + return this; + } + + /** + * Get a value indicating whether multi VM sync enabled VMs should use multi VM sync points for failover. + * + * @return the useMultiVmSyncPoint value + */ + public String useMultiVmSyncPoint() { + return this.useMultiVmSyncPoint; + } + + /** + * Set a value indicating whether multi VM sync enabled VMs should use multi VM sync points for failover. + * + * @param useMultiVmSyncPoint the useMultiVmSyncPoint value to set + * @return the RecoveryPlanInMageAzureV2FailoverInput object itself. + */ + public RecoveryPlanInMageAzureV2FailoverInput withUseMultiVmSyncPoint(String useMultiVmSyncPoint) { + this.useMultiVmSyncPoint = useMultiVmSyncPoint; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanInMageFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanInMageFailoverInput.java new file mode 100644 index 0000000000000..84fcd0b7fdb55 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanInMageFailoverInput.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Recovery plan InMage failover input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("InMage") +public class RecoveryPlanInMageFailoverInput extends RecoveryPlanProviderSpecificFailoverInput { + /** + * The recovery point type. Possible values include: 'LatestTime', + * 'LatestTag', 'Custom'. + */ + @JsonProperty(value = "recoveryPointType", required = true) + private RpInMageRecoveryPointType recoveryPointType; + + /** + * Get the recovery point type. Possible values include: 'LatestTime', 'LatestTag', 'Custom'. + * + * @return the recoveryPointType value + */ + public RpInMageRecoveryPointType recoveryPointType() { + return this.recoveryPointType; + } + + /** + * Set the recovery point type. Possible values include: 'LatestTime', 'LatestTag', 'Custom'. + * + * @param recoveryPointType the recoveryPointType value to set + * @return the RecoveryPlanInMageFailoverInput object itself. + */ + public RecoveryPlanInMageFailoverInput withRecoveryPointType(RpInMageRecoveryPointType recoveryPointType) { + this.recoveryPointType = recoveryPointType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanManualActionDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanManualActionDetails.java new file mode 100644 index 0000000000000..37dffa760e2ad --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanManualActionDetails.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Recovery plan manual action details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ManualActionDetails") +public class RecoveryPlanManualActionDetails extends RecoveryPlanActionDetails { + /** + * The manual action description. + */ + @JsonProperty(value = "description") + private String description; + + /** + * Get the manual action description. + * + * @return the description value + */ + public String description() { + return this.description; + } + + /** + * Set the manual action description. + * + * @param description the description value to set + * @return the RecoveryPlanManualActionDetails object itself. + */ + public RecoveryPlanManualActionDetails withDescription(String description) { + this.description = description; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanPlannedFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanPlannedFailoverInput.java new file mode 100644 index 0000000000000..5ce4a0368eaa2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanPlannedFailoverInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan planned failover input. + */ +public class RecoveryPlanPlannedFailoverInput { + /** + * The recovery plan planned failover input properties. + */ + @JsonProperty(value = "properties", required = true) + private RecoveryPlanPlannedFailoverInputProperties properties; + + /** + * Get the recovery plan planned failover input properties. + * + * @return the properties value + */ + public RecoveryPlanPlannedFailoverInputProperties properties() { + return this.properties; + } + + /** + * Set the recovery plan planned failover input properties. + * + * @param properties the properties value to set + * @return the RecoveryPlanPlannedFailoverInput object itself. + */ + public RecoveryPlanPlannedFailoverInput withProperties(RecoveryPlanPlannedFailoverInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanPlannedFailoverInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanPlannedFailoverInputProperties.java new file mode 100644 index 0000000000000..d972d84f159ef --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanPlannedFailoverInputProperties.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan planned failover input properties. + */ +public class RecoveryPlanPlannedFailoverInputProperties { + /** + * The failover direction. Possible values include: 'PrimaryToRecovery', + * 'RecoveryToPrimary'. + */ + @JsonProperty(value = "failoverDirection", required = true) + private PossibleOperationsDirections failoverDirection; + + /** + * The provider specific properties. + */ + @JsonProperty(value = "providerSpecificDetails") + private List providerSpecificDetails; + + /** + * Get the failover direction. Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'. + * + * @return the failoverDirection value + */ + public PossibleOperationsDirections failoverDirection() { + return this.failoverDirection; + } + + /** + * Set the failover direction. Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'. + * + * @param failoverDirection the failoverDirection value to set + * @return the RecoveryPlanPlannedFailoverInputProperties object itself. + */ + public RecoveryPlanPlannedFailoverInputProperties withFailoverDirection(PossibleOperationsDirections failoverDirection) { + this.failoverDirection = failoverDirection; + return this; + } + + /** + * Get the provider specific properties. + * + * @return the providerSpecificDetails value + */ + public List providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific properties. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the RecoveryPlanPlannedFailoverInputProperties object itself. + */ + public RecoveryPlanPlannedFailoverInputProperties withProviderSpecificDetails(List providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProperties.java new file mode 100644 index 0000000000000..632ebefad5ef1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProperties.java @@ -0,0 +1,409 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan custom details. + */ +public class RecoveryPlanProperties { + /** + * The friendly name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The primary fabric Id. + */ + @JsonProperty(value = "primaryFabricId") + private String primaryFabricId; + + /** + * The primary fabric friendly name. + */ + @JsonProperty(value = "primaryFabricFriendlyName") + private String primaryFabricFriendlyName; + + /** + * The recovery fabric Id. + */ + @JsonProperty(value = "recoveryFabricId") + private String recoveryFabricId; + + /** + * The recovery fabric friendly name. + */ + @JsonProperty(value = "recoveryFabricFriendlyName") + private String recoveryFabricFriendlyName; + + /** + * The failover deployment model. + */ + @JsonProperty(value = "failoverDeploymentModel") + private String failoverDeploymentModel; + + /** + * The list of replication providers. + */ + @JsonProperty(value = "replicationProviders") + private List replicationProviders; + + /** + * The list of allowed operations. + */ + @JsonProperty(value = "allowedOperations") + private List allowedOperations; + + /** + * The start time of the last planned failover. + */ + @JsonProperty(value = "lastPlannedFailoverTime") + private DateTime lastPlannedFailoverTime; + + /** + * The start time of the last unplanned failover. + */ + @JsonProperty(value = "lastUnplannedFailoverTime") + private DateTime lastUnplannedFailoverTime; + + /** + * The start time of the last test failover. + */ + @JsonProperty(value = "lastTestFailoverTime") + private DateTime lastTestFailoverTime; + + /** + * The current scenario details. + */ + @JsonProperty(value = "currentScenario") + private CurrentScenarioDetails currentScenario; + + /** + * The recovery plan status. + */ + @JsonProperty(value = "currentScenarioStatus") + private String currentScenarioStatus; + + /** + * The recovery plan status description. + */ + @JsonProperty(value = "currentScenarioStatusDescription") + private String currentScenarioStatusDescription; + + /** + * The recovery plan groups. + */ + @JsonProperty(value = "groups") + private List groups; + + /** + * Get the friendly name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the friendly name. + * + * @param friendlyName the friendlyName value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the primary fabric Id. + * + * @return the primaryFabricId value + */ + public String primaryFabricId() { + return this.primaryFabricId; + } + + /** + * Set the primary fabric Id. + * + * @param primaryFabricId the primaryFabricId value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withPrimaryFabricId(String primaryFabricId) { + this.primaryFabricId = primaryFabricId; + return this; + } + + /** + * Get the primary fabric friendly name. + * + * @return the primaryFabricFriendlyName value + */ + public String primaryFabricFriendlyName() { + return this.primaryFabricFriendlyName; + } + + /** + * Set the primary fabric friendly name. + * + * @param primaryFabricFriendlyName the primaryFabricFriendlyName value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withPrimaryFabricFriendlyName(String primaryFabricFriendlyName) { + this.primaryFabricFriendlyName = primaryFabricFriendlyName; + return this; + } + + /** + * Get the recovery fabric Id. + * + * @return the recoveryFabricId value + */ + public String recoveryFabricId() { + return this.recoveryFabricId; + } + + /** + * Set the recovery fabric Id. + * + * @param recoveryFabricId the recoveryFabricId value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withRecoveryFabricId(String recoveryFabricId) { + this.recoveryFabricId = recoveryFabricId; + return this; + } + + /** + * Get the recovery fabric friendly name. + * + * @return the recoveryFabricFriendlyName value + */ + public String recoveryFabricFriendlyName() { + return this.recoveryFabricFriendlyName; + } + + /** + * Set the recovery fabric friendly name. + * + * @param recoveryFabricFriendlyName the recoveryFabricFriendlyName value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withRecoveryFabricFriendlyName(String recoveryFabricFriendlyName) { + this.recoveryFabricFriendlyName = recoveryFabricFriendlyName; + return this; + } + + /** + * Get the failover deployment model. + * + * @return the failoverDeploymentModel value + */ + public String failoverDeploymentModel() { + return this.failoverDeploymentModel; + } + + /** + * Set the failover deployment model. + * + * @param failoverDeploymentModel the failoverDeploymentModel value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withFailoverDeploymentModel(String failoverDeploymentModel) { + this.failoverDeploymentModel = failoverDeploymentModel; + return this; + } + + /** + * Get the list of replication providers. + * + * @return the replicationProviders value + */ + public List replicationProviders() { + return this.replicationProviders; + } + + /** + * Set the list of replication providers. + * + * @param replicationProviders the replicationProviders value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withReplicationProviders(List replicationProviders) { + this.replicationProviders = replicationProviders; + return this; + } + + /** + * Get the list of allowed operations. + * + * @return the allowedOperations value + */ + public List allowedOperations() { + return this.allowedOperations; + } + + /** + * Set the list of allowed operations. + * + * @param allowedOperations the allowedOperations value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withAllowedOperations(List allowedOperations) { + this.allowedOperations = allowedOperations; + return this; + } + + /** + * Get the start time of the last planned failover. + * + * @return the lastPlannedFailoverTime value + */ + public DateTime lastPlannedFailoverTime() { + return this.lastPlannedFailoverTime; + } + + /** + * Set the start time of the last planned failover. + * + * @param lastPlannedFailoverTime the lastPlannedFailoverTime value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withLastPlannedFailoverTime(DateTime lastPlannedFailoverTime) { + this.lastPlannedFailoverTime = lastPlannedFailoverTime; + return this; + } + + /** + * Get the start time of the last unplanned failover. + * + * @return the lastUnplannedFailoverTime value + */ + public DateTime lastUnplannedFailoverTime() { + return this.lastUnplannedFailoverTime; + } + + /** + * Set the start time of the last unplanned failover. + * + * @param lastUnplannedFailoverTime the lastUnplannedFailoverTime value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withLastUnplannedFailoverTime(DateTime lastUnplannedFailoverTime) { + this.lastUnplannedFailoverTime = lastUnplannedFailoverTime; + return this; + } + + /** + * Get the start time of the last test failover. + * + * @return the lastTestFailoverTime value + */ + public DateTime lastTestFailoverTime() { + return this.lastTestFailoverTime; + } + + /** + * Set the start time of the last test failover. + * + * @param lastTestFailoverTime the lastTestFailoverTime value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withLastTestFailoverTime(DateTime lastTestFailoverTime) { + this.lastTestFailoverTime = lastTestFailoverTime; + return this; + } + + /** + * Get the current scenario details. + * + * @return the currentScenario value + */ + public CurrentScenarioDetails currentScenario() { + return this.currentScenario; + } + + /** + * Set the current scenario details. + * + * @param currentScenario the currentScenario value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withCurrentScenario(CurrentScenarioDetails currentScenario) { + this.currentScenario = currentScenario; + return this; + } + + /** + * Get the recovery plan status. + * + * @return the currentScenarioStatus value + */ + public String currentScenarioStatus() { + return this.currentScenarioStatus; + } + + /** + * Set the recovery plan status. + * + * @param currentScenarioStatus the currentScenarioStatus value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withCurrentScenarioStatus(String currentScenarioStatus) { + this.currentScenarioStatus = currentScenarioStatus; + return this; + } + + /** + * Get the recovery plan status description. + * + * @return the currentScenarioStatusDescription value + */ + public String currentScenarioStatusDescription() { + return this.currentScenarioStatusDescription; + } + + /** + * Set the recovery plan status description. + * + * @param currentScenarioStatusDescription the currentScenarioStatusDescription value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withCurrentScenarioStatusDescription(String currentScenarioStatusDescription) { + this.currentScenarioStatusDescription = currentScenarioStatusDescription; + return this; + } + + /** + * Get the recovery plan groups. + * + * @return the groups value + */ + public List groups() { + return this.groups; + } + + /** + * Set the recovery plan groups. + * + * @param groups the groups value to set + * @return the RecoveryPlanProperties object itself. + */ + public RecoveryPlanProperties withGroups(List groups) { + this.groups = groups; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProtectedItem.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProtectedItem.java new file mode 100644 index 0000000000000..d06ebd618285d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProtectedItem.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan protected item. + */ +public class RecoveryPlanProtectedItem { + /** + * The ARM Id of the recovery plan protected item. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The virtual machine Id. + */ + @JsonProperty(value = "virtualMachineId") + private String virtualMachineId; + + /** + * Get the ARM Id of the recovery plan protected item. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the ARM Id of the recovery plan protected item. + * + * @param id the id value to set + * @return the RecoveryPlanProtectedItem object itself. + */ + public RecoveryPlanProtectedItem withId(String id) { + this.id = id; + return this; + } + + /** + * Get the virtual machine Id. + * + * @return the virtualMachineId value + */ + public String virtualMachineId() { + return this.virtualMachineId; + } + + /** + * Set the virtual machine Id. + * + * @param virtualMachineId the virtualMachineId value to set + * @return the RecoveryPlanProtectedItem object itself. + */ + public RecoveryPlanProtectedItem withVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProviderSpecificFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProviderSpecificFailoverInput.java new file mode 100644 index 0000000000000..2749bc35641a3 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanProviderSpecificFailoverInput.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Recovery plan provider specific failover input base class. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("RecoveryPlanProviderSpecificFailoverInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = RecoveryPlanA2AFailoverInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzureFailback", value = RecoveryPlanHyperVReplicaAzureFailbackInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = RecoveryPlanHyperVReplicaAzureFailoverInput.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = RecoveryPlanInMageAzureV2FailoverInput.class), + @JsonSubTypes.Type(name = "InMage", value = RecoveryPlanInMageFailoverInput.class) +}) +public class RecoveryPlanProviderSpecificFailoverInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanScriptActionDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanScriptActionDetails.java new file mode 100644 index 0000000000000..1411b9bf43544 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanScriptActionDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Recovery plan script action details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ScriptActionDetails") +public class RecoveryPlanScriptActionDetails extends RecoveryPlanActionDetails { + /** + * The script path. + */ + @JsonProperty(value = "path", required = true) + private String path; + + /** + * The script timeout. + */ + @JsonProperty(value = "timeout") + private String timeout; + + /** + * The fabric location. Possible values include: 'Primary', 'Recovery'. + */ + @JsonProperty(value = "fabricLocation", required = true) + private RecoveryPlanActionLocation fabricLocation; + + /** + * Get the script path. + * + * @return the path value + */ + public String path() { + return this.path; + } + + /** + * Set the script path. + * + * @param path the path value to set + * @return the RecoveryPlanScriptActionDetails object itself. + */ + public RecoveryPlanScriptActionDetails withPath(String path) { + this.path = path; + return this; + } + + /** + * Get the script timeout. + * + * @return the timeout value + */ + public String timeout() { + return this.timeout; + } + + /** + * Set the script timeout. + * + * @param timeout the timeout value to set + * @return the RecoveryPlanScriptActionDetails object itself. + */ + public RecoveryPlanScriptActionDetails withTimeout(String timeout) { + this.timeout = timeout; + return this; + } + + /** + * Get the fabric location. Possible values include: 'Primary', 'Recovery'. + * + * @return the fabricLocation value + */ + public RecoveryPlanActionLocation fabricLocation() { + return this.fabricLocation; + } + + /** + * Set the fabric location. Possible values include: 'Primary', 'Recovery'. + * + * @param fabricLocation the fabricLocation value to set + * @return the RecoveryPlanScriptActionDetails object itself. + */ + public RecoveryPlanScriptActionDetails withFabricLocation(RecoveryPlanActionLocation fabricLocation) { + this.fabricLocation = fabricLocation; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanShutdownGroupTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanShutdownGroupTaskDetails.java new file mode 100644 index 0000000000000..f228ef0310240 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanShutdownGroupTaskDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the recovery plan shutdown group task details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("RecoveryPlanShutdownGroupTaskDetails") +public class RecoveryPlanShutdownGroupTaskDetails extends GroupTaskDetails { + /** + * The name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The group identifier. + */ + @JsonProperty(value = "groupId") + private String groupId; + + /** + * The group type. + */ + @JsonProperty(value = "rpGroupType") + private String rpGroupType; + + /** + * Get the name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name. + * + * @param name the name value to set + * @return the RecoveryPlanShutdownGroupTaskDetails object itself. + */ + public RecoveryPlanShutdownGroupTaskDetails withName(String name) { + this.name = name; + return this; + } + + /** + * Get the group identifier. + * + * @return the groupId value + */ + public String groupId() { + return this.groupId; + } + + /** + * Set the group identifier. + * + * @param groupId the groupId value to set + * @return the RecoveryPlanShutdownGroupTaskDetails object itself. + */ + public RecoveryPlanShutdownGroupTaskDetails withGroupId(String groupId) { + this.groupId = groupId; + return this; + } + + /** + * Get the group type. + * + * @return the rpGroupType value + */ + public String rpGroupType() { + return this.rpGroupType; + } + + /** + * Set the group type. + * + * @param rpGroupType the rpGroupType value to set + * @return the RecoveryPlanShutdownGroupTaskDetails object itself. + */ + public RecoveryPlanShutdownGroupTaskDetails withRpGroupType(String rpGroupType) { + this.rpGroupType = rpGroupType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverCleanupInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverCleanupInput.java new file mode 100644 index 0000000000000..0ab742f56aa16 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverCleanupInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan test failover cleanup input. + */ +public class RecoveryPlanTestFailoverCleanupInput { + /** + * The recovery plan test failover cleanup input properties. + */ + @JsonProperty(value = "properties", required = true) + private RecoveryPlanTestFailoverCleanupInputProperties properties; + + /** + * Get the recovery plan test failover cleanup input properties. + * + * @return the properties value + */ + public RecoveryPlanTestFailoverCleanupInputProperties properties() { + return this.properties; + } + + /** + * Set the recovery plan test failover cleanup input properties. + * + * @param properties the properties value to set + * @return the RecoveryPlanTestFailoverCleanupInput object itself. + */ + public RecoveryPlanTestFailoverCleanupInput withProperties(RecoveryPlanTestFailoverCleanupInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverCleanupInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverCleanupInputProperties.java new file mode 100644 index 0000000000000..52232dd0f3e7d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverCleanupInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan test failover cleanup input properties. + */ +public class RecoveryPlanTestFailoverCleanupInputProperties { + /** + * The test failover cleanup comments. + */ + @JsonProperty(value = "comments") + private String comments; + + /** + * Get the test failover cleanup comments. + * + * @return the comments value + */ + public String comments() { + return this.comments; + } + + /** + * Set the test failover cleanup comments. + * + * @param comments the comments value to set + * @return the RecoveryPlanTestFailoverCleanupInputProperties object itself. + */ + public RecoveryPlanTestFailoverCleanupInputProperties withComments(String comments) { + this.comments = comments; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverInput.java new file mode 100644 index 0000000000000..806c6d1147b20 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan test failover input. + */ +public class RecoveryPlanTestFailoverInput { + /** + * The recovery plan test failover input properties. + */ + @JsonProperty(value = "properties", required = true) + private RecoveryPlanTestFailoverInputProperties properties; + + /** + * Get the recovery plan test failover input properties. + * + * @return the properties value + */ + public RecoveryPlanTestFailoverInputProperties properties() { + return this.properties; + } + + /** + * Set the recovery plan test failover input properties. + * + * @param properties the properties value to set + * @return the RecoveryPlanTestFailoverInput object itself. + */ + public RecoveryPlanTestFailoverInput withProperties(RecoveryPlanTestFailoverInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverInputProperties.java new file mode 100644 index 0000000000000..bba17f050cb5f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanTestFailoverInputProperties.java @@ -0,0 +1,149 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan test failover input properties. + */ +public class RecoveryPlanTestFailoverInputProperties { + /** + * The failover direction. Possible values include: 'PrimaryToRecovery', + * 'RecoveryToPrimary'. + */ + @JsonProperty(value = "failoverDirection", required = true) + private PossibleOperationsDirections failoverDirection; + + /** + * The network type to be used for test failover. + */ + @JsonProperty(value = "networkType", required = true) + private String networkType; + + /** + * The Id of the network to be used for test failover. + */ + @JsonProperty(value = "networkId") + private String networkId; + + /** + * A value indicating whether the test failover cleanup is to be skipped. + */ + @JsonProperty(value = "skipTestFailoverCleanup") + private String skipTestFailoverCleanup; + + /** + * The provider specific properties. + */ + @JsonProperty(value = "providerSpecificDetails") + private List providerSpecificDetails; + + /** + * Get the failover direction. Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'. + * + * @return the failoverDirection value + */ + public PossibleOperationsDirections failoverDirection() { + return this.failoverDirection; + } + + /** + * Set the failover direction. Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'. + * + * @param failoverDirection the failoverDirection value to set + * @return the RecoveryPlanTestFailoverInputProperties object itself. + */ + public RecoveryPlanTestFailoverInputProperties withFailoverDirection(PossibleOperationsDirections failoverDirection) { + this.failoverDirection = failoverDirection; + return this; + } + + /** + * Get the network type to be used for test failover. + * + * @return the networkType value + */ + public String networkType() { + return this.networkType; + } + + /** + * Set the network type to be used for test failover. + * + * @param networkType the networkType value to set + * @return the RecoveryPlanTestFailoverInputProperties object itself. + */ + public RecoveryPlanTestFailoverInputProperties withNetworkType(String networkType) { + this.networkType = networkType; + return this; + } + + /** + * Get the Id of the network to be used for test failover. + * + * @return the networkId value + */ + public String networkId() { + return this.networkId; + } + + /** + * Set the Id of the network to be used for test failover. + * + * @param networkId the networkId value to set + * @return the RecoveryPlanTestFailoverInputProperties object itself. + */ + public RecoveryPlanTestFailoverInputProperties withNetworkId(String networkId) { + this.networkId = networkId; + return this; + } + + /** + * Get a value indicating whether the test failover cleanup is to be skipped. + * + * @return the skipTestFailoverCleanup value + */ + public String skipTestFailoverCleanup() { + return this.skipTestFailoverCleanup; + } + + /** + * Set a value indicating whether the test failover cleanup is to be skipped. + * + * @param skipTestFailoverCleanup the skipTestFailoverCleanup value to set + * @return the RecoveryPlanTestFailoverInputProperties object itself. + */ + public RecoveryPlanTestFailoverInputProperties withSkipTestFailoverCleanup(String skipTestFailoverCleanup) { + this.skipTestFailoverCleanup = skipTestFailoverCleanup; + return this; + } + + /** + * Get the provider specific properties. + * + * @return the providerSpecificDetails value + */ + public List providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific properties. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the RecoveryPlanTestFailoverInputProperties object itself. + */ + public RecoveryPlanTestFailoverInputProperties withProviderSpecificDetails(List providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanUnplannedFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanUnplannedFailoverInput.java new file mode 100644 index 0000000000000..945b6b663681a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanUnplannedFailoverInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan unplanned failover input. + */ +public class RecoveryPlanUnplannedFailoverInput { + /** + * The recovery plan unplanned failover input properties. + */ + @JsonProperty(value = "properties", required = true) + private RecoveryPlanUnplannedFailoverInputProperties properties; + + /** + * Get the recovery plan unplanned failover input properties. + * + * @return the properties value + */ + public RecoveryPlanUnplannedFailoverInputProperties properties() { + return this.properties; + } + + /** + * Set the recovery plan unplanned failover input properties. + * + * @param properties the properties value to set + * @return the RecoveryPlanUnplannedFailoverInput object itself. + */ + public RecoveryPlanUnplannedFailoverInput withProperties(RecoveryPlanUnplannedFailoverInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanUnplannedFailoverInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanUnplannedFailoverInputProperties.java new file mode 100644 index 0000000000000..dd11d8de3cdc5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPlanUnplannedFailoverInputProperties.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan unplanned failover input properties. + */ +public class RecoveryPlanUnplannedFailoverInputProperties { + /** + * The failover direction. Possible values include: 'PrimaryToRecovery', + * 'RecoveryToPrimary'. + */ + @JsonProperty(value = "failoverDirection", required = true) + private PossibleOperationsDirections failoverDirection; + + /** + * A value indicating whether source site operations are required. Possible + * values include: 'Required', 'NotRequired'. + */ + @JsonProperty(value = "sourceSiteOperations", required = true) + private SourceSiteOperations sourceSiteOperations; + + /** + * The provider specific properties. + */ + @JsonProperty(value = "providerSpecificDetails") + private List providerSpecificDetails; + + /** + * Get the failover direction. Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'. + * + * @return the failoverDirection value + */ + public PossibleOperationsDirections failoverDirection() { + return this.failoverDirection; + } + + /** + * Set the failover direction. Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'. + * + * @param failoverDirection the failoverDirection value to set + * @return the RecoveryPlanUnplannedFailoverInputProperties object itself. + */ + public RecoveryPlanUnplannedFailoverInputProperties withFailoverDirection(PossibleOperationsDirections failoverDirection) { + this.failoverDirection = failoverDirection; + return this; + } + + /** + * Get a value indicating whether source site operations are required. Possible values include: 'Required', 'NotRequired'. + * + * @return the sourceSiteOperations value + */ + public SourceSiteOperations sourceSiteOperations() { + return this.sourceSiteOperations; + } + + /** + * Set a value indicating whether source site operations are required. Possible values include: 'Required', 'NotRequired'. + * + * @param sourceSiteOperations the sourceSiteOperations value to set + * @return the RecoveryPlanUnplannedFailoverInputProperties object itself. + */ + public RecoveryPlanUnplannedFailoverInputProperties withSourceSiteOperations(SourceSiteOperations sourceSiteOperations) { + this.sourceSiteOperations = sourceSiteOperations; + return this; + } + + /** + * Get the provider specific properties. + * + * @return the providerSpecificDetails value + */ + public List providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific properties. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the RecoveryPlanUnplannedFailoverInputProperties object itself. + */ + public RecoveryPlanUnplannedFailoverInputProperties withProviderSpecificDetails(List providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPoint.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPoint.java new file mode 100644 index 0000000000000..783c88670f532 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPoint.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryPointInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing RecoveryPoint. + */ +public interface RecoveryPoint extends HasInner, Indexable, Refreshable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + RecoveryPointProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointProperties.java new file mode 100644 index 0000000000000..11206331e8d17 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointProperties.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery point properties. + */ +public class RecoveryPointProperties { + /** + * The recovery point time. + */ + @JsonProperty(value = "recoveryPointTime") + private DateTime recoveryPointTime; + + /** + * The recovery point type: ApplicationConsistent, CrashConsistent. + */ + @JsonProperty(value = "recoveryPointType") + private String recoveryPointType; + + /** + * The provider specific details for the recovery point. + */ + @JsonProperty(value = "providerSpecificDetails") + private ProviderSpecificRecoveryPointDetails providerSpecificDetails; + + /** + * Get the recovery point time. + * + * @return the recoveryPointTime value + */ + public DateTime recoveryPointTime() { + return this.recoveryPointTime; + } + + /** + * Set the recovery point time. + * + * @param recoveryPointTime the recoveryPointTime value to set + * @return the RecoveryPointProperties object itself. + */ + public RecoveryPointProperties withRecoveryPointTime(DateTime recoveryPointTime) { + this.recoveryPointTime = recoveryPointTime; + return this; + } + + /** + * Get the recovery point type: ApplicationConsistent, CrashConsistent. + * + * @return the recoveryPointType value + */ + public String recoveryPointType() { + return this.recoveryPointType; + } + + /** + * Set the recovery point type: ApplicationConsistent, CrashConsistent. + * + * @param recoveryPointType the recoveryPointType value to set + * @return the RecoveryPointProperties object itself. + */ + public RecoveryPointProperties withRecoveryPointType(String recoveryPointType) { + this.recoveryPointType = recoveryPointType; + return this; + } + + /** + * Get the provider specific details for the recovery point. + * + * @return the providerSpecificDetails value + */ + public ProviderSpecificRecoveryPointDetails providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific details for the recovery point. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the RecoveryPointProperties object itself. + */ + public RecoveryPointProperties withProviderSpecificDetails(ProviderSpecificRecoveryPointDetails providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointSyncType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointSyncType.java new file mode 100644 index 0000000000000..7f9bf26000446 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointSyncType.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for RecoveryPointSyncType. + */ +public final class RecoveryPointSyncType extends ExpandableStringEnum { + /** Static value MultiVmSyncRecoveryPoint for RecoveryPointSyncType. */ + public static final RecoveryPointSyncType MULTI_VM_SYNC_RECOVERY_POINT = fromString("MultiVmSyncRecoveryPoint"); + + /** Static value PerVmRecoveryPoint for RecoveryPointSyncType. */ + public static final RecoveryPointSyncType PER_VM_RECOVERY_POINT = fromString("PerVmRecoveryPoint"); + + /** + * Creates or finds a RecoveryPointSyncType from its string representation. + * @param name a name to look for + * @return the corresponding RecoveryPointSyncType + */ + @JsonCreator + public static RecoveryPointSyncType fromString(String name) { + return fromString(name, RecoveryPointSyncType.class); + } + + /** + * @return known RecoveryPointSyncType values + */ + public static Collection values() { + return values(RecoveryPointSyncType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointType.java new file mode 100644 index 0000000000000..b4cba1c2d0729 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPointType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for RecoveryPointType. + */ +public final class RecoveryPointType extends ExpandableStringEnum { + /** Static value LatestTime for RecoveryPointType. */ + public static final RecoveryPointType LATEST_TIME = fromString("LatestTime"); + + /** Static value LatestTag for RecoveryPointType. */ + public static final RecoveryPointType LATEST_TAG = fromString("LatestTag"); + + /** Static value Custom for RecoveryPointType. */ + public static final RecoveryPointType CUSTOM = fromString("Custom"); + + /** + * Creates or finds a RecoveryPointType from its string representation. + * @param name a name to look for + * @return the corresponding RecoveryPointType + */ + @JsonCreator + public static RecoveryPointType fromString(String name) { + return fromString(name, RecoveryPointType.class); + } + + /** + * @return known RecoveryPointType values + */ + public static Collection values() { + return values(RecoveryPointType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPoints.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPoints.java new file mode 100644 index 0000000000000..5481dc2917c9c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryPoints.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryPointsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing RecoveryPoints. + */ +public interface RecoveryPoints extends HasInner { + /** + * Get a recovery point. + * Get the details of specified recovery point. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @param recoveryPointName The recovery point name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, String recoveryPointName); + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationProtectedItemsAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryServicesProvider.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryServicesProvider.java new file mode 100644 index 0000000000000..4c9f7e47ecbf7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryServicesProvider.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesProviderInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing RecoveryServicesProvider. + */ +public interface RecoveryServicesProvider extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + RecoveryServicesProviderProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the RecoveryServicesProvider definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithReplicationFabric, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of RecoveryServicesProvider definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a RecoveryServicesProvider definition. + */ + interface Blank extends WithReplicationFabric { + } + + /** + * The stage of the recoveryservicesprovider definition allowing to specify ReplicationFabric. + */ + interface WithReplicationFabric { + /** + * Specifies fabricName. + * @param fabricName Fabric name + * @return the next definition stage + */ + WithProperties withExistingReplicationFabric(String fabricName); + } + + /** + * The stage of the recoveryservicesprovider definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties The properties of an add provider request + * @return the next definition stage + */ + WithCreate withProperties(AddRecoveryServicesProviderInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a RecoveryServicesProvider update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of RecoveryServicesProvider update stages. + */ + interface UpdateStages { + /** + * The stage of the recoveryservicesprovider update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties The properties of an add provider request + * @return the next update stage + */ + Update withProperties(AddRecoveryServicesProviderInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryServicesProviderProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryServicesProviderProperties.java new file mode 100644 index 0000000000000..810a65e5cdca5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RecoveryServicesProviderProperties.java @@ -0,0 +1,435 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery services provider properties. + */ +public class RecoveryServicesProviderProperties { + /** + * Type of the site. + */ + @JsonProperty(value = "fabricType") + private String fabricType; + + /** + * Friendly name of the DRA. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The provider version. + */ + @JsonProperty(value = "providerVersion") + private String providerVersion; + + /** + * The fabric provider. + */ + @JsonProperty(value = "serverVersion") + private String serverVersion; + + /** + * DRA version status. + */ + @JsonProperty(value = "providerVersionState") + private String providerVersionState; + + /** + * Expiry date of the version. + */ + @JsonProperty(value = "providerVersionExpiryDate") + private DateTime providerVersionExpiryDate; + + /** + * The fabric friendly name. + */ + @JsonProperty(value = "fabricFriendlyName") + private String fabricFriendlyName; + + /** + * Time when last heartbeat was sent by the DRA. + */ + @JsonProperty(value = "lastHeartBeat") + private DateTime lastHeartBeat; + + /** + * A value indicating whether DRA is responsive. + */ + @JsonProperty(value = "connectionStatus") + private String connectionStatus; + + /** + * Number of protected VMs currently managed by the DRA. + */ + @JsonProperty(value = "protectedItemCount") + private Integer protectedItemCount; + + /** + * The scenarios allowed on this provider. + */ + @JsonProperty(value = "allowedScenarios") + private List allowedScenarios; + + /** + * The recovery services provider health error details. + */ + @JsonProperty(value = "healthErrorDetails") + private List healthErrorDetails; + + /** + * The DRA Id. + */ + @JsonProperty(value = "draIdentifier") + private String draIdentifier; + + /** + * The authentication identity details. + */ + @JsonProperty(value = "authenticationIdentityDetails") + private IdentityProviderDetails authenticationIdentityDetails; + + /** + * The resource access identity details. + */ + @JsonProperty(value = "resourceAccessIdentityDetails") + private IdentityProviderDetails resourceAccessIdentityDetails; + + /** + * The provider version details. + */ + @JsonProperty(value = "providerVersionDetails") + private VersionDetails providerVersionDetails; + + /** + * Get type of the site. + * + * @return the fabricType value + */ + public String fabricType() { + return this.fabricType; + } + + /** + * Set type of the site. + * + * @param fabricType the fabricType value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withFabricType(String fabricType) { + this.fabricType = fabricType; + return this; + } + + /** + * Get friendly name of the DRA. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set friendly name of the DRA. + * + * @param friendlyName the friendlyName value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the provider version. + * + * @return the providerVersion value + */ + public String providerVersion() { + return this.providerVersion; + } + + /** + * Set the provider version. + * + * @param providerVersion the providerVersion value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withProviderVersion(String providerVersion) { + this.providerVersion = providerVersion; + return this; + } + + /** + * Get the fabric provider. + * + * @return the serverVersion value + */ + public String serverVersion() { + return this.serverVersion; + } + + /** + * Set the fabric provider. + * + * @param serverVersion the serverVersion value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withServerVersion(String serverVersion) { + this.serverVersion = serverVersion; + return this; + } + + /** + * Get dRA version status. + * + * @return the providerVersionState value + */ + public String providerVersionState() { + return this.providerVersionState; + } + + /** + * Set dRA version status. + * + * @param providerVersionState the providerVersionState value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withProviderVersionState(String providerVersionState) { + this.providerVersionState = providerVersionState; + return this; + } + + /** + * Get expiry date of the version. + * + * @return the providerVersionExpiryDate value + */ + public DateTime providerVersionExpiryDate() { + return this.providerVersionExpiryDate; + } + + /** + * Set expiry date of the version. + * + * @param providerVersionExpiryDate the providerVersionExpiryDate value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withProviderVersionExpiryDate(DateTime providerVersionExpiryDate) { + this.providerVersionExpiryDate = providerVersionExpiryDate; + return this; + } + + /** + * Get the fabric friendly name. + * + * @return the fabricFriendlyName value + */ + public String fabricFriendlyName() { + return this.fabricFriendlyName; + } + + /** + * Set the fabric friendly name. + * + * @param fabricFriendlyName the fabricFriendlyName value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withFabricFriendlyName(String fabricFriendlyName) { + this.fabricFriendlyName = fabricFriendlyName; + return this; + } + + /** + * Get time when last heartbeat was sent by the DRA. + * + * @return the lastHeartBeat value + */ + public DateTime lastHeartBeat() { + return this.lastHeartBeat; + } + + /** + * Set time when last heartbeat was sent by the DRA. + * + * @param lastHeartBeat the lastHeartBeat value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withLastHeartBeat(DateTime lastHeartBeat) { + this.lastHeartBeat = lastHeartBeat; + return this; + } + + /** + * Get a value indicating whether DRA is responsive. + * + * @return the connectionStatus value + */ + public String connectionStatus() { + return this.connectionStatus; + } + + /** + * Set a value indicating whether DRA is responsive. + * + * @param connectionStatus the connectionStatus value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withConnectionStatus(String connectionStatus) { + this.connectionStatus = connectionStatus; + return this; + } + + /** + * Get number of protected VMs currently managed by the DRA. + * + * @return the protectedItemCount value + */ + public Integer protectedItemCount() { + return this.protectedItemCount; + } + + /** + * Set number of protected VMs currently managed by the DRA. + * + * @param protectedItemCount the protectedItemCount value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withProtectedItemCount(Integer protectedItemCount) { + this.protectedItemCount = protectedItemCount; + return this; + } + + /** + * Get the scenarios allowed on this provider. + * + * @return the allowedScenarios value + */ + public List allowedScenarios() { + return this.allowedScenarios; + } + + /** + * Set the scenarios allowed on this provider. + * + * @param allowedScenarios the allowedScenarios value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withAllowedScenarios(List allowedScenarios) { + this.allowedScenarios = allowedScenarios; + return this; + } + + /** + * Get the recovery services provider health error details. + * + * @return the healthErrorDetails value + */ + public List healthErrorDetails() { + return this.healthErrorDetails; + } + + /** + * Set the recovery services provider health error details. + * + * @param healthErrorDetails the healthErrorDetails value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withHealthErrorDetails(List healthErrorDetails) { + this.healthErrorDetails = healthErrorDetails; + return this; + } + + /** + * Get the DRA Id. + * + * @return the draIdentifier value + */ + public String draIdentifier() { + return this.draIdentifier; + } + + /** + * Set the DRA Id. + * + * @param draIdentifier the draIdentifier value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withDraIdentifier(String draIdentifier) { + this.draIdentifier = draIdentifier; + return this; + } + + /** + * Get the authentication identity details. + * + * @return the authenticationIdentityDetails value + */ + public IdentityProviderDetails authenticationIdentityDetails() { + return this.authenticationIdentityDetails; + } + + /** + * Set the authentication identity details. + * + * @param authenticationIdentityDetails the authenticationIdentityDetails value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withAuthenticationIdentityDetails(IdentityProviderDetails authenticationIdentityDetails) { + this.authenticationIdentityDetails = authenticationIdentityDetails; + return this; + } + + /** + * Get the resource access identity details. + * + * @return the resourceAccessIdentityDetails value + */ + public IdentityProviderDetails resourceAccessIdentityDetails() { + return this.resourceAccessIdentityDetails; + } + + /** + * Set the resource access identity details. + * + * @param resourceAccessIdentityDetails the resourceAccessIdentityDetails value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withResourceAccessIdentityDetails(IdentityProviderDetails resourceAccessIdentityDetails) { + this.resourceAccessIdentityDetails = resourceAccessIdentityDetails; + return this; + } + + /** + * Get the provider version details. + * + * @return the providerVersionDetails value + */ + public VersionDetails providerVersionDetails() { + return this.providerVersionDetails; + } + + /** + * Set the provider version details. + * + * @param providerVersionDetails the providerVersionDetails value to set + * @return the RecoveryServicesProviderProperties object itself. + */ + public RecoveryServicesProviderProperties withProviderVersionDetails(VersionDetails providerVersionDetails) { + this.providerVersionDetails = providerVersionDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RemoveProtectionContainerMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RemoveProtectionContainerMappingInput.java new file mode 100644 index 0000000000000..0862fb7676754 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RemoveProtectionContainerMappingInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Container unpairing input. + */ +public class RemoveProtectionContainerMappingInput { + /** + * Configure protection input properties. + */ + @JsonProperty(value = "properties") + private RemoveProtectionContainerMappingInputProperties properties; + + /** + * Get configure protection input properties. + * + * @return the properties value + */ + public RemoveProtectionContainerMappingInputProperties properties() { + return this.properties; + } + + /** + * Set configure protection input properties. + * + * @param properties the properties value to set + * @return the RemoveProtectionContainerMappingInput object itself. + */ + public RemoveProtectionContainerMappingInput withProperties(RemoveProtectionContainerMappingInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RemoveProtectionContainerMappingInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RemoveProtectionContainerMappingInputProperties.java new file mode 100644 index 0000000000000..879dc8e70c20a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RemoveProtectionContainerMappingInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Unpairing input properties. + */ +public class RemoveProtectionContainerMappingInputProperties { + /** + * Provider specific input for unpairing. + */ + @JsonProperty(value = "providerSpecificInput") + private ReplicationProviderContainerUnmappingInput providerSpecificInput; + + /** + * Get provider specific input for unpairing. + * + * @return the providerSpecificInput value + */ + public ReplicationProviderContainerUnmappingInput providerSpecificInput() { + return this.providerSpecificInput; + } + + /** + * Set provider specific input for unpairing. + * + * @param providerSpecificInput the providerSpecificInput value to set + * @return the RemoveProtectionContainerMappingInputProperties object itself. + */ + public RemoveProtectionContainerMappingInputProperties withProviderSpecificInput(ReplicationProviderContainerUnmappingInput providerSpecificInput) { + this.providerSpecificInput = providerSpecificInput; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RenewCertificateInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RenewCertificateInput.java new file mode 100644 index 0000000000000..b0acae6663ec6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RenewCertificateInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Certificate renewal input. + */ +public class RenewCertificateInput { + /** + * Renew certificate input properties. + */ + @JsonProperty(value = "properties") + private RenewCertificateInputProperties properties; + + /** + * Get renew certificate input properties. + * + * @return the properties value + */ + public RenewCertificateInputProperties properties() { + return this.properties; + } + + /** + * Set renew certificate input properties. + * + * @param properties the properties value to set + * @return the RenewCertificateInput object itself. + */ + public RenewCertificateInput withProperties(RenewCertificateInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RenewCertificateInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RenewCertificateInputProperties.java new file mode 100644 index 0000000000000..49d34defce8f2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RenewCertificateInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Renew Certificate input properties. + */ +public class RenewCertificateInputProperties { + /** + * Renew certificate type. + */ + @JsonProperty(value = "renewCertificateType") + private String renewCertificateType; + + /** + * Get renew certificate type. + * + * @return the renewCertificateType value + */ + public String renewCertificateType() { + return this.renewCertificateType; + } + + /** + * Set renew certificate type. + * + * @param renewCertificateType the renewCertificateType value to set + * @return the RenewCertificateInputProperties object itself. + */ + public RenewCertificateInputProperties withRenewCertificateType(String renewCertificateType) { + this.renewCertificateType = renewCertificateType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationAlertSettings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationAlertSettings.java new file mode 100644 index 0000000000000..dd80eb8cde2c2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationAlertSettings.java @@ -0,0 +1,39 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationAlertSettingsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationAlertSettings. + */ +public interface ReplicationAlertSettings extends SupportsCreating, HasInner { + /** + * Gets an email notification(alert) configuration. + * Gets the details of the specified email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification configuration. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String alertSettingName); + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationEvents.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationEvents.java new file mode 100644 index 0000000000000..fc4a1bd92be8f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationEvents.java @@ -0,0 +1,38 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationEventsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationEvents. + */ +public interface ReplicationEvents extends HasInner { + /** + * Get the details of an Azure Site recovery event. + * The operation to get the details of an Azure Site recovery event. + * + * @param eventName The name of the Azure Site Recovery event. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String eventName); + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationFabrics.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationFabrics.java new file mode 100644 index 0000000000000..ebaf6eafdd9d2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationFabrics.java @@ -0,0 +1,100 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationFabricsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationFabrics. + */ +public interface ReplicationFabrics extends SupportsCreating, HasInner { + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable checkConsistencyAsync(String fabricName); + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable migrateToAadAsync(String fabricName); + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable reassociateGatewayAsync(String fabricName); + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName); + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable renewCertificateAsync(String fabricName); + + /** + * Gets the details of an ASR fabric. + * Gets the details of an Azure Site Recovery fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName); + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable purgeAsync(String fabricName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationGroupDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationGroupDetails.java new file mode 100644 index 0000000000000..11df6a969490f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationGroupDetails.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Replication group details. This will be used in case of San and Wvr. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ReplicationGroupDetails") +public class ReplicationGroupDetails extends ConfigurationSettings { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationJobs.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationJobs.java new file mode 100644 index 0000000000000..f2b2bf33fca73 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationJobs.java @@ -0,0 +1,78 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationJobsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationJobs. + */ +public interface ReplicationJobs extends HasInner { + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable cancelAsync(String jobName); + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable restartAsync(String jobName); + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable resumeAsync(String jobName); + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable exportAsync(JobQueryParameter jobQueryParameter); + + /** + * Gets the job details. + * Get the details of an Azure Site Recovery job. + * + * @param jobName Job identifier + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String jobName); + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationLogicalNetworks.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationLogicalNetworks.java new file mode 100644 index 0000000000000..9eef22b7825ed --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationLogicalNetworks.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationLogicalNetworksInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationLogicalNetworks. + */ +public interface ReplicationLogicalNetworks extends HasInner { + /** + * Gets a logical network with specified server id and logical network name. + * Gets the details of a logical network. + * + * @param fabricName Server Id. + * @param logicalNetworkName Logical network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String logicalNetworkName); + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param fabricName Server Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationFabricsAsync(final String fabricName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationMigrationItems.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationMigrationItems.java new file mode 100644 index 0000000000000..1e10b3d7fe532 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationMigrationItems.java @@ -0,0 +1,102 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationMigrationItemsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationMigrationItems. + */ +public interface ReplicationMigrationItems extends SupportsCreating, HasInner { + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable migrateAsync(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties); + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable testMigrateAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties); + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable testMigrateCleanupAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties); + + /** + * Gets the list of migration items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets the details of a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String protectionContainerName, String migrationItemName); + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName); + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName, String protectionContainerName, String migrationItemName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationNetworkMappings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationNetworkMappings.java new file mode 100644 index 0000000000000..e809f0174af5f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationNetworkMappings.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationNetworkMappingsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationNetworkMappings. + */ +public interface ReplicationNetworkMappings extends SupportsCreating, HasInner { + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets network mapping by name. + * Gets the details of an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String networkName, String networkMappingName); + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationNetworksAsync(final String fabricName, final String networkName); + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName, String networkName, String networkMappingName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationNetworks.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationNetworks.java new file mode 100644 index 0000000000000..58bf9870a6ee2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationNetworks.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationNetworksInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationNetworks. + */ +public interface ReplicationNetworks extends HasInner { + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets a network with specified server id and network name. + * Gets the details of a network. + * + * @param fabricName Server Id. + * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String networkName); + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationFabricsAsync(final String fabricName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationPolicies.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationPolicies.java new file mode 100644 index 0000000000000..8a873e219b108 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationPolicies.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationPoliciesInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationPolicies. + */ +public interface ReplicationPolicies extends SupportsCreating, HasInner { + /** + * Gets the requested policy. + * Gets the details of a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String policyName); + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String policyName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectableItems.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectableItems.java new file mode 100644 index 0000000000000..1459a713b6b0d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectableItems.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationProtectableItemsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationProtectableItems. + */ +public interface ReplicationProtectableItems extends HasInner { + /** + * Gets the details of a protectable item. + * The operation to get the details of a protectable item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param protectableItemName Protectable item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String protectionContainerName, String protectableItemName); + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItem.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItem.java new file mode 100644 index 0000000000000..e86152e0c2888 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItem.java @@ -0,0 +1,123 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationProtectedItemInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; +import java.util.List; + +/** + * Type representing ReplicationProtectedItem. + */ +public interface ReplicationProtectedItem extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + ReplicationProtectedItemProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the ReplicationProtectedItem definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithReplicationProtectionContainer, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of ReplicationProtectedItem definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a ReplicationProtectedItem definition. + */ + interface Blank extends WithReplicationProtectionContainer { + } + + /** + * The stage of the replicationprotecteditem definition allowing to specify ReplicationProtectionContainer. + */ + interface WithReplicationProtectionContainer { + /** + * Specifies fabricName, protectionContainerName. + * @param fabricName Name of the fabric + * @param protectionContainerName Protection container name + * @return the next definition stage + */ + WithProperties withExistingReplicationProtectionContainer(String fabricName, String protectionContainerName); + } + + /** + * The stage of the replicationprotecteditem definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Enable protection input properties + * @return the next definition stage + */ + WithCreate withProperties(EnableProtectionInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a ReplicationProtectedItem update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of ReplicationProtectedItem update stages. + */ + interface UpdateStages { + /** + * The stage of the replicationprotecteditem update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Update replication protected item properties + * @return the next update stage + */ + Update withProperties(UpdateReplicationProtectedItemInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItemOperation.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItemOperation.java new file mode 100644 index 0000000000000..9d03d507e3802 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItemOperation.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for ReplicationProtectedItemOperation. + */ +public final class ReplicationProtectedItemOperation extends ExpandableStringEnum { + /** Static value ReverseReplicate for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation REVERSE_REPLICATE = fromString("ReverseReplicate"); + + /** Static value Commit for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation COMMIT = fromString("Commit"); + + /** Static value PlannedFailover for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation PLANNED_FAILOVER = fromString("PlannedFailover"); + + /** Static value UnplannedFailover for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation UNPLANNED_FAILOVER = fromString("UnplannedFailover"); + + /** Static value DisableProtection for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation DISABLE_PROTECTION = fromString("DisableProtection"); + + /** Static value TestFailover for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation TEST_FAILOVER = fromString("TestFailover"); + + /** Static value TestFailoverCleanup for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation TEST_FAILOVER_CLEANUP = fromString("TestFailoverCleanup"); + + /** Static value Failback for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation FAILBACK = fromString("Failback"); + + /** Static value FinalizeFailback for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation FINALIZE_FAILBACK = fromString("FinalizeFailback"); + + /** Static value ChangePit for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation CHANGE_PIT = fromString("ChangePit"); + + /** Static value RepairReplication for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation REPAIR_REPLICATION = fromString("RepairReplication"); + + /** Static value SwitchProtection for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation SWITCH_PROTECTION = fromString("SwitchProtection"); + + /** Static value CompleteMigration for ReplicationProtectedItemOperation. */ + public static final ReplicationProtectedItemOperation COMPLETE_MIGRATION = fromString("CompleteMigration"); + + /** + * Creates or finds a ReplicationProtectedItemOperation from its string representation. + * @param name a name to look for + * @return the corresponding ReplicationProtectedItemOperation + */ + @JsonCreator + public static ReplicationProtectedItemOperation fromString(String name) { + return fromString(name, ReplicationProtectedItemOperation.class); + } + + /** + * @return known ReplicationProtectedItemOperation values + */ + public static Collection values() { + return values(ReplicationProtectedItemOperation.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItemProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItemProperties.java new file mode 100644 index 0000000000000..f72b769f3f8cc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItemProperties.java @@ -0,0 +1,724 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Replication protected item custom data details. + */ +public class ReplicationProtectedItemProperties { + /** + * The name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The type of protected item type. + */ + @JsonProperty(value = "protectedItemType") + private String protectedItemType; + + /** + * The protected item ARM Id. + */ + @JsonProperty(value = "protectableItemId") + private String protectableItemId; + + /** + * The recovery provider ARM Id. + */ + @JsonProperty(value = "recoveryServicesProviderId") + private String recoveryServicesProviderId; + + /** + * The friendly name of the primary fabric. + */ + @JsonProperty(value = "primaryFabricFriendlyName") + private String primaryFabricFriendlyName; + + /** + * The fabric provider of the primary fabric. + */ + @JsonProperty(value = "primaryFabricProvider") + private String primaryFabricProvider; + + /** + * The friendly name of recovery fabric. + */ + @JsonProperty(value = "recoveryFabricFriendlyName") + private String recoveryFabricFriendlyName; + + /** + * The Arm Id of recovery fabric. + */ + @JsonProperty(value = "recoveryFabricId") + private String recoveryFabricId; + + /** + * The name of primary protection container friendly name. + */ + @JsonProperty(value = "primaryProtectionContainerFriendlyName") + private String primaryProtectionContainerFriendlyName; + + /** + * The name of recovery container friendly name. + */ + @JsonProperty(value = "recoveryProtectionContainerFriendlyName") + private String recoveryProtectionContainerFriendlyName; + + /** + * The protection status. + */ + @JsonProperty(value = "protectionState") + private String protectionState; + + /** + * The protection state description. + */ + @JsonProperty(value = "protectionStateDescription") + private String protectionStateDescription; + + /** + * The Current active location of the PE. + */ + @JsonProperty(value = "activeLocation") + private String activeLocation; + + /** + * The Test failover state. + */ + @JsonProperty(value = "testFailoverState") + private String testFailoverState; + + /** + * The Test failover state description. + */ + @JsonProperty(value = "testFailoverStateDescription") + private String testFailoverStateDescription; + + /** + * The allowed operations on the Replication protected item. + */ + @JsonProperty(value = "allowedOperations") + private List allowedOperations; + + /** + * The consolidated protection health for the VM taking any issues with SRS + * as well as all the replication units associated with the VM's + * replication group into account. This is a string representation of the + * ProtectionHealth enumeration. + */ + @JsonProperty(value = "replicationHealth") + private String replicationHealth; + + /** + * The consolidated failover health for the VM. + */ + @JsonProperty(value = "failoverHealth") + private String failoverHealth; + + /** + * List of health errors. + */ + @JsonProperty(value = "healthErrors") + private List healthErrors; + + /** + * The ID of Policy governing this PE. + */ + @JsonProperty(value = "policyId") + private String policyId; + + /** + * The name of Policy governing this PE. + */ + @JsonProperty(value = "policyFriendlyName") + private String policyFriendlyName; + + /** + * The Last successful failover time. + */ + @JsonProperty(value = "lastSuccessfulFailoverTime") + private DateTime lastSuccessfulFailoverTime; + + /** + * The Last successful test failover time. + */ + @JsonProperty(value = "lastSuccessfulTestFailoverTime") + private DateTime lastSuccessfulTestFailoverTime; + + /** + * The current scenario. + */ + @JsonProperty(value = "currentScenario") + private CurrentScenarioDetails currentScenario; + + /** + * The recovery point ARM Id to which the Vm was failed over. + */ + @JsonProperty(value = "failoverRecoveryPointId") + private String failoverRecoveryPointId; + + /** + * The Replication provider custom settings. + */ + @JsonProperty(value = "providerSpecificDetails") + private ReplicationProviderSpecificSettings providerSpecificDetails; + + /** + * The recovery container Id. + */ + @JsonProperty(value = "recoveryContainerId") + private String recoveryContainerId; + + /** + * Get the name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the name. + * + * @param friendlyName the friendlyName value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the type of protected item type. + * + * @return the protectedItemType value + */ + public String protectedItemType() { + return this.protectedItemType; + } + + /** + * Set the type of protected item type. + * + * @param protectedItemType the protectedItemType value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withProtectedItemType(String protectedItemType) { + this.protectedItemType = protectedItemType; + return this; + } + + /** + * Get the protected item ARM Id. + * + * @return the protectableItemId value + */ + public String protectableItemId() { + return this.protectableItemId; + } + + /** + * Set the protected item ARM Id. + * + * @param protectableItemId the protectableItemId value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withProtectableItemId(String protectableItemId) { + this.protectableItemId = protectableItemId; + return this; + } + + /** + * Get the recovery provider ARM Id. + * + * @return the recoveryServicesProviderId value + */ + public String recoveryServicesProviderId() { + return this.recoveryServicesProviderId; + } + + /** + * Set the recovery provider ARM Id. + * + * @param recoveryServicesProviderId the recoveryServicesProviderId value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withRecoveryServicesProviderId(String recoveryServicesProviderId) { + this.recoveryServicesProviderId = recoveryServicesProviderId; + return this; + } + + /** + * Get the friendly name of the primary fabric. + * + * @return the primaryFabricFriendlyName value + */ + public String primaryFabricFriendlyName() { + return this.primaryFabricFriendlyName; + } + + /** + * Set the friendly name of the primary fabric. + * + * @param primaryFabricFriendlyName the primaryFabricFriendlyName value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withPrimaryFabricFriendlyName(String primaryFabricFriendlyName) { + this.primaryFabricFriendlyName = primaryFabricFriendlyName; + return this; + } + + /** + * Get the fabric provider of the primary fabric. + * + * @return the primaryFabricProvider value + */ + public String primaryFabricProvider() { + return this.primaryFabricProvider; + } + + /** + * Set the fabric provider of the primary fabric. + * + * @param primaryFabricProvider the primaryFabricProvider value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withPrimaryFabricProvider(String primaryFabricProvider) { + this.primaryFabricProvider = primaryFabricProvider; + return this; + } + + /** + * Get the friendly name of recovery fabric. + * + * @return the recoveryFabricFriendlyName value + */ + public String recoveryFabricFriendlyName() { + return this.recoveryFabricFriendlyName; + } + + /** + * Set the friendly name of recovery fabric. + * + * @param recoveryFabricFriendlyName the recoveryFabricFriendlyName value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withRecoveryFabricFriendlyName(String recoveryFabricFriendlyName) { + this.recoveryFabricFriendlyName = recoveryFabricFriendlyName; + return this; + } + + /** + * Get the Arm Id of recovery fabric. + * + * @return the recoveryFabricId value + */ + public String recoveryFabricId() { + return this.recoveryFabricId; + } + + /** + * Set the Arm Id of recovery fabric. + * + * @param recoveryFabricId the recoveryFabricId value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withRecoveryFabricId(String recoveryFabricId) { + this.recoveryFabricId = recoveryFabricId; + return this; + } + + /** + * Get the name of primary protection container friendly name. + * + * @return the primaryProtectionContainerFriendlyName value + */ + public String primaryProtectionContainerFriendlyName() { + return this.primaryProtectionContainerFriendlyName; + } + + /** + * Set the name of primary protection container friendly name. + * + * @param primaryProtectionContainerFriendlyName the primaryProtectionContainerFriendlyName value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withPrimaryProtectionContainerFriendlyName(String primaryProtectionContainerFriendlyName) { + this.primaryProtectionContainerFriendlyName = primaryProtectionContainerFriendlyName; + return this; + } + + /** + * Get the name of recovery container friendly name. + * + * @return the recoveryProtectionContainerFriendlyName value + */ + public String recoveryProtectionContainerFriendlyName() { + return this.recoveryProtectionContainerFriendlyName; + } + + /** + * Set the name of recovery container friendly name. + * + * @param recoveryProtectionContainerFriendlyName the recoveryProtectionContainerFriendlyName value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withRecoveryProtectionContainerFriendlyName(String recoveryProtectionContainerFriendlyName) { + this.recoveryProtectionContainerFriendlyName = recoveryProtectionContainerFriendlyName; + return this; + } + + /** + * Get the protection status. + * + * @return the protectionState value + */ + public String protectionState() { + return this.protectionState; + } + + /** + * Set the protection status. + * + * @param protectionState the protectionState value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withProtectionState(String protectionState) { + this.protectionState = protectionState; + return this; + } + + /** + * Get the protection state description. + * + * @return the protectionStateDescription value + */ + public String protectionStateDescription() { + return this.protectionStateDescription; + } + + /** + * Set the protection state description. + * + * @param protectionStateDescription the protectionStateDescription value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withProtectionStateDescription(String protectionStateDescription) { + this.protectionStateDescription = protectionStateDescription; + return this; + } + + /** + * Get the Current active location of the PE. + * + * @return the activeLocation value + */ + public String activeLocation() { + return this.activeLocation; + } + + /** + * Set the Current active location of the PE. + * + * @param activeLocation the activeLocation value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withActiveLocation(String activeLocation) { + this.activeLocation = activeLocation; + return this; + } + + /** + * Get the Test failover state. + * + * @return the testFailoverState value + */ + public String testFailoverState() { + return this.testFailoverState; + } + + /** + * Set the Test failover state. + * + * @param testFailoverState the testFailoverState value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withTestFailoverState(String testFailoverState) { + this.testFailoverState = testFailoverState; + return this; + } + + /** + * Get the Test failover state description. + * + * @return the testFailoverStateDescription value + */ + public String testFailoverStateDescription() { + return this.testFailoverStateDescription; + } + + /** + * Set the Test failover state description. + * + * @param testFailoverStateDescription the testFailoverStateDescription value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withTestFailoverStateDescription(String testFailoverStateDescription) { + this.testFailoverStateDescription = testFailoverStateDescription; + return this; + } + + /** + * Get the allowed operations on the Replication protected item. + * + * @return the allowedOperations value + */ + public List allowedOperations() { + return this.allowedOperations; + } + + /** + * Set the allowed operations on the Replication protected item. + * + * @param allowedOperations the allowedOperations value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withAllowedOperations(List allowedOperations) { + this.allowedOperations = allowedOperations; + return this; + } + + /** + * Get the consolidated protection health for the VM taking any issues with SRS as well as all the replication units associated with the VM's replication group into account. This is a string representation of the ProtectionHealth enumeration. + * + * @return the replicationHealth value + */ + public String replicationHealth() { + return this.replicationHealth; + } + + /** + * Set the consolidated protection health for the VM taking any issues with SRS as well as all the replication units associated with the VM's replication group into account. This is a string representation of the ProtectionHealth enumeration. + * + * @param replicationHealth the replicationHealth value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withReplicationHealth(String replicationHealth) { + this.replicationHealth = replicationHealth; + return this; + } + + /** + * Get the consolidated failover health for the VM. + * + * @return the failoverHealth value + */ + public String failoverHealth() { + return this.failoverHealth; + } + + /** + * Set the consolidated failover health for the VM. + * + * @param failoverHealth the failoverHealth value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withFailoverHealth(String failoverHealth) { + this.failoverHealth = failoverHealth; + return this; + } + + /** + * Get list of health errors. + * + * @return the healthErrors value + */ + public List healthErrors() { + return this.healthErrors; + } + + /** + * Set list of health errors. + * + * @param healthErrors the healthErrors value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withHealthErrors(List healthErrors) { + this.healthErrors = healthErrors; + return this; + } + + /** + * Get the ID of Policy governing this PE. + * + * @return the policyId value + */ + public String policyId() { + return this.policyId; + } + + /** + * Set the ID of Policy governing this PE. + * + * @param policyId the policyId value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withPolicyId(String policyId) { + this.policyId = policyId; + return this; + } + + /** + * Get the name of Policy governing this PE. + * + * @return the policyFriendlyName value + */ + public String policyFriendlyName() { + return this.policyFriendlyName; + } + + /** + * Set the name of Policy governing this PE. + * + * @param policyFriendlyName the policyFriendlyName value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withPolicyFriendlyName(String policyFriendlyName) { + this.policyFriendlyName = policyFriendlyName; + return this; + } + + /** + * Get the Last successful failover time. + * + * @return the lastSuccessfulFailoverTime value + */ + public DateTime lastSuccessfulFailoverTime() { + return this.lastSuccessfulFailoverTime; + } + + /** + * Set the Last successful failover time. + * + * @param lastSuccessfulFailoverTime the lastSuccessfulFailoverTime value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withLastSuccessfulFailoverTime(DateTime lastSuccessfulFailoverTime) { + this.lastSuccessfulFailoverTime = lastSuccessfulFailoverTime; + return this; + } + + /** + * Get the Last successful test failover time. + * + * @return the lastSuccessfulTestFailoverTime value + */ + public DateTime lastSuccessfulTestFailoverTime() { + return this.lastSuccessfulTestFailoverTime; + } + + /** + * Set the Last successful test failover time. + * + * @param lastSuccessfulTestFailoverTime the lastSuccessfulTestFailoverTime value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withLastSuccessfulTestFailoverTime(DateTime lastSuccessfulTestFailoverTime) { + this.lastSuccessfulTestFailoverTime = lastSuccessfulTestFailoverTime; + return this; + } + + /** + * Get the current scenario. + * + * @return the currentScenario value + */ + public CurrentScenarioDetails currentScenario() { + return this.currentScenario; + } + + /** + * Set the current scenario. + * + * @param currentScenario the currentScenario value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withCurrentScenario(CurrentScenarioDetails currentScenario) { + this.currentScenario = currentScenario; + return this; + } + + /** + * Get the recovery point ARM Id to which the Vm was failed over. + * + * @return the failoverRecoveryPointId value + */ + public String failoverRecoveryPointId() { + return this.failoverRecoveryPointId; + } + + /** + * Set the recovery point ARM Id to which the Vm was failed over. + * + * @param failoverRecoveryPointId the failoverRecoveryPointId value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withFailoverRecoveryPointId(String failoverRecoveryPointId) { + this.failoverRecoveryPointId = failoverRecoveryPointId; + return this; + } + + /** + * Get the Replication provider custom settings. + * + * @return the providerSpecificDetails value + */ + public ReplicationProviderSpecificSettings providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the Replication provider custom settings. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withProviderSpecificDetails(ReplicationProviderSpecificSettings providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + + /** + * Get the recovery container Id. + * + * @return the recoveryContainerId value + */ + public String recoveryContainerId() { + return this.recoveryContainerId; + } + + /** + * Set the recovery container Id. + * + * @param recoveryContainerId the recoveryContainerId value to set + * @return the ReplicationProtectedItemProperties object itself. + */ + public ReplicationProtectedItemProperties withRecoveryContainerId(String recoveryContainerId) { + this.recoveryContainerId = recoveryContainerId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItems.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItems.java new file mode 100644 index 0000000000000..98bf5f0e76a3a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectedItems.java @@ -0,0 +1,186 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationProtectedItemsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationProtectedItems. + */ +public interface ReplicationProtectedItems extends SupportsCreating, HasInner { + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable applyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable failoverCommitAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable plannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable repairReplicationAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable reprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable testFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable testFailoverCleanupAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties); + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable unplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable updateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName); + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets the details of a Replication protected item. + * Gets the details of an ASR replication protected item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName); + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable purgeAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectionContainerMappings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectionContainerMappings.java new file mode 100644 index 0000000000000..a78bd705d22d6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectionContainerMappings.java @@ -0,0 +1,77 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationProtectionContainerMappingsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationProtectionContainerMappings. + */ +public interface ReplicationProtectionContainerMappings extends SupportsCreating, HasInner { + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName, String protectionContainerName, String mappingName); + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets a protection container mapping/. + * Gets the details of a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection Container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String protectionContainerName, String mappingName); + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName); + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable purgeAsync(String fabricName, String protectionContainerName, String mappingName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectionContainers.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectionContainers.java new file mode 100644 index 0000000000000..6a9417b3a5339 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProtectionContainers.java @@ -0,0 +1,84 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Observable; +import rx.Completable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationProtectionContainersInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationProtectionContainers. + */ +public interface ReplicationProtectionContainers extends SupportsCreating, HasInner { + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable discoverProtectableItemAsync(String fabricName, String protectionContainerName); + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName, String protectionContainerName); + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable switchProtectionAsync(String fabricName, String protectionContainerName); + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets the protection container details. + * Gets the details of a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String protectionContainerName); + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationFabricsAsync(final String fabricName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderContainerUnmappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderContainerUnmappingInput.java new file mode 100644 index 0000000000000..2a1d162f59a78 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderContainerUnmappingInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Provider specific input for unpairing operations. + */ +public class ReplicationProviderContainerUnmappingInput { + /** + * The class type. + */ + @JsonProperty(value = "instanceType") + private String instanceType; + + /** + * Get the class type. + * + * @return the instanceType value + */ + public String instanceType() { + return this.instanceType; + } + + /** + * Set the class type. + * + * @param instanceType the instanceType value to set + * @return the ReplicationProviderContainerUnmappingInput object itself. + */ + public ReplicationProviderContainerUnmappingInput withInstanceType(String instanceType) { + this.instanceType = instanceType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificContainerCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificContainerCreationInput.java new file mode 100644 index 0000000000000..343b5ea9e2e42 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificContainerCreationInput.java @@ -0,0 +1,25 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Provider specific input for container creation operation. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ReplicationProviderSpecificContainerCreationInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AContainerCreationInput.class), + @JsonSubTypes.Type(name = "6c7da455-506f-43ff-a16a-8eb101aebb70", value = VMwareCbtContainerCreationInput.class) +}) +public class ReplicationProviderSpecificContainerCreationInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificContainerMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificContainerMappingInput.java new file mode 100644 index 0000000000000..5fd36a97cade6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificContainerMappingInput.java @@ -0,0 +1,25 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Provider specific input for pairing operations. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ReplicationProviderSpecificContainerMappingInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AContainerMappingInput.class), + @JsonSubTypes.Type(name = "VMwareCbt", value = VMwareCbtContainerMappingInput.class) +}) +public class ReplicationProviderSpecificContainerMappingInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificSettings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificSettings.java new file mode 100644 index 0000000000000..eacd9bf37e5b1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificSettings.java @@ -0,0 +1,30 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Replication provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ReplicationProviderSpecificSettings") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AReplicationDetails.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzureReplicationDetails.class), + @JsonSubTypes.Type(name = "HyperVReplicaBaseReplicationDetails", value = HyperVReplicaBaseReplicationDetails.class), + @JsonSubTypes.Type(name = "HyperVReplica2012R2", value = HyperVReplicaBlueReplicationDetails.class), + @JsonSubTypes.Type(name = "HyperVReplica2012", value = HyperVReplicaReplicationDetails.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2ReplicationDetails.class), + @JsonSubTypes.Type(name = "InMage", value = InMageReplicationDetails.class) +}) +public class ReplicationProviderSpecificSettings { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificUpdateContainerMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificUpdateContainerMappingInput.java new file mode 100644 index 0000000000000..01b7c2dc7a2f5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationProviderSpecificUpdateContainerMappingInput.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Provider specific input for update pairing operations. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ReplicationProviderSpecificUpdateContainerMappingInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AUpdateContainerMappingInput.class) +}) +public class ReplicationProviderSpecificUpdateContainerMappingInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationRecoveryPlans.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationRecoveryPlans.java new file mode 100644 index 0000000000000..5f2de19d7865d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationRecoveryPlans.java @@ -0,0 +1,114 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationRecoveryPlansInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationRecoveryPlans. + */ +public interface ReplicationRecoveryPlans extends SupportsCreating, HasInner { + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable failoverCommitAsync(String recoveryPlanName); + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable plannedFailoverAsync(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties); + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable reprotectAsync(String recoveryPlanName); + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable testFailoverAsync(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties); + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable testFailoverCleanupAsync(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties); + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable unplannedFailoverAsync(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties); + + /** + * Gets the requested recovery plan. + * Gets the details of the recovery plan. + * + * @param recoveryPlanName Name of the recovery plan. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String recoveryPlanName); + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String recoveryPlanName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationRecoveryServicesProviders.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationRecoveryServicesProviders.java new file mode 100644 index 0000000000000..3472d195985ec --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationRecoveryServicesProviders.java @@ -0,0 +1,84 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationRecoveryServicesProvidersInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationRecoveryServicesProviders. + */ +public interface ReplicationRecoveryServicesProviders extends SupportsCreating, HasInner { + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable refreshProviderAsync(String fabricName, String providerName); + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName, String providerName); + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets the details of a recovery services provider. + * Gets the details of registered recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String providerName); + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationFabricsAsync(final String fabricName); + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable purgeAsync(String fabricName, String providerName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationStorageClassificationMappings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationStorageClassificationMappings.java new file mode 100644 index 0000000000000..f9db4f7ae022f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationStorageClassificationMappings.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationStorageClassificationMappingsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationStorageClassificationMappings. + */ +public interface ReplicationStorageClassificationMappings extends SupportsCreating, HasInner { + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets the details of a storage classification mapping. + * Gets the details of the specified storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName); + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationStorageClassificationsAsync(final String fabricName, final String storageClassificationName); + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationStorageClassifications.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationStorageClassifications.java new file mode 100644 index 0000000000000..614962575b76f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationStorageClassifications.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationStorageClassificationsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationStorageClassifications. + */ +public interface ReplicationStorageClassifications extends HasInner { + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets the details of a storage classification. + * Gets the details of the specified storage classification. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String storageClassificationName); + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param fabricName Site name of interest. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationFabricsAsync(final String fabricName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationVaultHealths.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationVaultHealths.java new file mode 100644 index 0000000000000..e9e6872de7b3f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationVaultHealths.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationVaultHealthsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationVaultHealths. + */ +public interface ReplicationVaultHealths extends HasInner { + /** + * Gets the health summary for the vault. + * Gets the health details of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(); + + /** + * Refreshes health summary of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable refreshAsync(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationvCenters.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationvCenters.java new file mode 100644 index 0000000000000..f48dc66ac6a18 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReplicationvCenters.java @@ -0,0 +1,62 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.ReplicationvCentersInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing ReplicationvCenters. + */ +public interface ReplicationvCenters extends SupportsCreating, HasInner { + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + + /** + * Gets the details of a vCenter. + * Gets the details of a registered vCenter server(Add vCenter server.). + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String fabricName, String vCenterName); + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationFabricsAsync(final String fabricName); + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String fabricName, String vCenterName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResourceHealthSummary.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResourceHealthSummary.java new file mode 100644 index 0000000000000..5bb4629018d90 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResourceHealthSummary.java @@ -0,0 +1,72 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Base class to define the health summary of the resources contained under an + * Arm resource. + */ +public class ResourceHealthSummary { + /** + * The count of total resources under the container. + */ + @JsonProperty(value = "resourceCount") + private Integer resourceCount; + + /** + * The list of summary of health errors across the resources under the + * container. + */ + @JsonProperty(value = "issues") + private List issues; + + /** + * Get the count of total resources under the container. + * + * @return the resourceCount value + */ + public Integer resourceCount() { + return this.resourceCount; + } + + /** + * Set the count of total resources under the container. + * + * @param resourceCount the resourceCount value to set + * @return the ResourceHealthSummary object itself. + */ + public ResourceHealthSummary withResourceCount(Integer resourceCount) { + this.resourceCount = resourceCount; + return this; + } + + /** + * Get the list of summary of health errors across the resources under the container. + * + * @return the issues value + */ + public List issues() { + return this.issues; + } + + /** + * Set the list of summary of health errors across the resources under the container. + * + * @param issues the issues value to set + * @return the ResourceHealthSummary object itself. + */ + public ResourceHealthSummary withIssues(List issues) { + this.issues = issues; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResumeJobParams.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResumeJobParams.java new file mode 100644 index 0000000000000..dd9f499d73ea2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResumeJobParams.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Resume job params. + */ +public class ResumeJobParams { + /** + * Resume job properties. + */ + @JsonProperty(value = "properties") + private ResumeJobParamsProperties properties; + + /** + * Get resume job properties. + * + * @return the properties value + */ + public ResumeJobParamsProperties properties() { + return this.properties; + } + + /** + * Set resume job properties. + * + * @param properties the properties value to set + * @return the ResumeJobParams object itself. + */ + public ResumeJobParams withProperties(ResumeJobParamsProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResumeJobParamsProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResumeJobParamsProperties.java new file mode 100644 index 0000000000000..99fbb3d6b7d12 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ResumeJobParamsProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Resume job properties. + */ +public class ResumeJobParamsProperties { + /** + * Resume job comments. + */ + @JsonProperty(value = "comments") + private String comments; + + /** + * Get resume job comments. + * + * @return the comments value + */ + public String comments() { + return this.comments; + } + + /** + * Set resume job comments. + * + * @param comments the comments value to set + * @return the ResumeJobParamsProperties object itself. + */ + public ResumeJobParamsProperties withComments(String comments) { + this.comments = comments; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RetentionVolume.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RetentionVolume.java new file mode 100644 index 0000000000000..f4f0b1e12c62e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RetentionVolume.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The retention details of the MT. + */ +public class RetentionVolume { + /** + * The volume name. + */ + @JsonProperty(value = "volumeName") + private String volumeName; + + /** + * The volume capacity. + */ + @JsonProperty(value = "capacityInBytes") + private Long capacityInBytes; + + /** + * The free space available in this volume. + */ + @JsonProperty(value = "freeSpaceInBytes") + private Long freeSpaceInBytes; + + /** + * The threshold percentage. + */ + @JsonProperty(value = "thresholdPercentage") + private Integer thresholdPercentage; + + /** + * Get the volume name. + * + * @return the volumeName value + */ + public String volumeName() { + return this.volumeName; + } + + /** + * Set the volume name. + * + * @param volumeName the volumeName value to set + * @return the RetentionVolume object itself. + */ + public RetentionVolume withVolumeName(String volumeName) { + this.volumeName = volumeName; + return this; + } + + /** + * Get the volume capacity. + * + * @return the capacityInBytes value + */ + public Long capacityInBytes() { + return this.capacityInBytes; + } + + /** + * Set the volume capacity. + * + * @param capacityInBytes the capacityInBytes value to set + * @return the RetentionVolume object itself. + */ + public RetentionVolume withCapacityInBytes(Long capacityInBytes) { + this.capacityInBytes = capacityInBytes; + return this; + } + + /** + * Get the free space available in this volume. + * + * @return the freeSpaceInBytes value + */ + public Long freeSpaceInBytes() { + return this.freeSpaceInBytes; + } + + /** + * Set the free space available in this volume. + * + * @param freeSpaceInBytes the freeSpaceInBytes value to set + * @return the RetentionVolume object itself. + */ + public RetentionVolume withFreeSpaceInBytes(Long freeSpaceInBytes) { + this.freeSpaceInBytes = freeSpaceInBytes; + return this; + } + + /** + * Get the threshold percentage. + * + * @return the thresholdPercentage value + */ + public Integer thresholdPercentage() { + return this.thresholdPercentage; + } + + /** + * Set the threshold percentage. + * + * @param thresholdPercentage the thresholdPercentage value to set + * @return the RetentionVolume object itself. + */ + public RetentionVolume withThresholdPercentage(Integer thresholdPercentage) { + this.thresholdPercentage = thresholdPercentage; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationInput.java new file mode 100644 index 0000000000000..583273558e4d9 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Reverse replication input. + */ +public class ReverseReplicationInput { + /** + * Reverse replication properties. + */ + @JsonProperty(value = "properties") + private ReverseReplicationInputProperties properties; + + /** + * Get reverse replication properties. + * + * @return the properties value + */ + public ReverseReplicationInputProperties properties() { + return this.properties; + } + + /** + * Set reverse replication properties. + * + * @param properties the properties value to set + * @return the ReverseReplicationInput object itself. + */ + public ReverseReplicationInput withProperties(ReverseReplicationInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationInputProperties.java new file mode 100644 index 0000000000000..a754402079c02 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationInputProperties.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Reverse replication input properties. + */ +public class ReverseReplicationInputProperties { + /** + * Failover direction. + */ + @JsonProperty(value = "failoverDirection") + private String failoverDirection; + + /** + * Provider specific reverse replication input. + */ + @JsonProperty(value = "providerSpecificDetails") + private ReverseReplicationProviderSpecificInput providerSpecificDetails; + + /** + * Get failover direction. + * + * @return the failoverDirection value + */ + public String failoverDirection() { + return this.failoverDirection; + } + + /** + * Set failover direction. + * + * @param failoverDirection the failoverDirection value to set + * @return the ReverseReplicationInputProperties object itself. + */ + public ReverseReplicationInputProperties withFailoverDirection(String failoverDirection) { + this.failoverDirection = failoverDirection; + return this; + } + + /** + * Get provider specific reverse replication input. + * + * @return the providerSpecificDetails value + */ + public ReverseReplicationProviderSpecificInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set provider specific reverse replication input. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the ReverseReplicationInputProperties object itself. + */ + public ReverseReplicationInputProperties withProviderSpecificDetails(ReverseReplicationProviderSpecificInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationProviderSpecificInput.java new file mode 100644 index 0000000000000..5bdc2bf385e7c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ReverseReplicationProviderSpecificInput.java @@ -0,0 +1,27 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Provider specific reverse replication input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ReverseReplicationProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AReprotectInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzureReprotectInput.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2ReprotectInput.class), + @JsonSubTypes.Type(name = "InMage", value = InMageReprotectInput.class) +}) +public class ReverseReplicationProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RoleAssignment.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RoleAssignment.java new file mode 100644 index 0000000000000..f31543bb54a9f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RoleAssignment.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Azure role assignment details. + */ +public class RoleAssignment { + /** + * The ARM Id of the role assignment. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The name of the role assignment. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Role assignment scope. + */ + @JsonProperty(value = "scope") + private String scope; + + /** + * Principal Id. + */ + @JsonProperty(value = "principalId") + private String principalId; + + /** + * Role definition id. + */ + @JsonProperty(value = "roleDefinitionId") + private String roleDefinitionId; + + /** + * Get the ARM Id of the role assignment. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the ARM Id of the role assignment. + * + * @param id the id value to set + * @return the RoleAssignment object itself. + */ + public RoleAssignment withId(String id) { + this.id = id; + return this; + } + + /** + * Get the name of the role assignment. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name of the role assignment. + * + * @param name the name value to set + * @return the RoleAssignment object itself. + */ + public RoleAssignment withName(String name) { + this.name = name; + return this; + } + + /** + * Get role assignment scope. + * + * @return the scope value + */ + public String scope() { + return this.scope; + } + + /** + * Set role assignment scope. + * + * @param scope the scope value to set + * @return the RoleAssignment object itself. + */ + public RoleAssignment withScope(String scope) { + this.scope = scope; + return this; + } + + /** + * Get principal Id. + * + * @return the principalId value + */ + public String principalId() { + return this.principalId; + } + + /** + * Set principal Id. + * + * @param principalId the principalId value to set + * @return the RoleAssignment object itself. + */ + public RoleAssignment withPrincipalId(String principalId) { + this.principalId = principalId; + return this; + } + + /** + * Get role definition id. + * + * @return the roleDefinitionId value + */ + public String roleDefinitionId() { + return this.roleDefinitionId; + } + + /** + * Set role definition id. + * + * @param roleDefinitionId the roleDefinitionId value to set + * @return the RoleAssignment object itself. + */ + public RoleAssignment withRoleDefinitionId(String roleDefinitionId) { + this.roleDefinitionId = roleDefinitionId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RpInMageRecoveryPointType.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RpInMageRecoveryPointType.java new file mode 100644 index 0000000000000..97c1ce640e7bc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RpInMageRecoveryPointType.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for RpInMageRecoveryPointType. + */ +public final class RpInMageRecoveryPointType extends ExpandableStringEnum { + /** Static value LatestTime for RpInMageRecoveryPointType. */ + public static final RpInMageRecoveryPointType LATEST_TIME = fromString("LatestTime"); + + /** Static value LatestTag for RpInMageRecoveryPointType. */ + public static final RpInMageRecoveryPointType LATEST_TAG = fromString("LatestTag"); + + /** Static value Custom for RpInMageRecoveryPointType. */ + public static final RpInMageRecoveryPointType CUSTOM = fromString("Custom"); + + /** + * Creates or finds a RpInMageRecoveryPointType from its string representation. + * @param name a name to look for + * @return the corresponding RpInMageRecoveryPointType + */ + @JsonCreator + public static RpInMageRecoveryPointType fromString(String name) { + return fromString(name, RpInMageRecoveryPointType.class); + } + + /** + * @return known RpInMageRecoveryPointType values + */ + public static Collection values() { + return values(RpInMageRecoveryPointType.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RunAsAccount.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RunAsAccount.java new file mode 100644 index 0000000000000..5734e2ebcdcdd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/RunAsAccount.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * CS Accounts Details. + */ +public class RunAsAccount { + /** + * The CS RunAs account Id. + */ + @JsonProperty(value = "accountId") + private String accountId; + + /** + * The CS RunAs account name. + */ + @JsonProperty(value = "accountName") + private String accountName; + + /** + * Get the CS RunAs account Id. + * + * @return the accountId value + */ + public String accountId() { + return this.accountId; + } + + /** + * Set the CS RunAs account Id. + * + * @param accountId the accountId value to set + * @return the RunAsAccount object itself. + */ + public RunAsAccount withAccountId(String accountId) { + this.accountId = accountId; + return this; + } + + /** + * Get the CS RunAs account name. + * + * @return the accountName value + */ + public String accountName() { + return this.accountName; + } + + /** + * Set the CS RunAs account name. + * + * @param accountName the accountName value to set + * @return the RunAsAccount object itself. + */ + public RunAsAccount withAccountName(String accountName) { + this.accountName = accountName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SanEnableProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SanEnableProtectionInput.java new file mode 100644 index 0000000000000..782be30984138 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SanEnableProtectionInput.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * San enable protection provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("San") +public class SanEnableProtectionInput extends EnableProtectionProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ScriptActionTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ScriptActionTaskDetails.java new file mode 100644 index 0000000000000..bd10b981e28b4 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ScriptActionTaskDetails.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the script action task details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("ScriptActionTaskDetails") +public class ScriptActionTaskDetails extends TaskTypeDetails { + /** + * The name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The path. + */ + @JsonProperty(value = "path") + private String path; + + /** + * The output. + */ + @JsonProperty(value = "output") + private String output; + + /** + * A value indicating whether it is a primary side script or not. + */ + @JsonProperty(value = "isPrimarySideScript") + private Boolean isPrimarySideScript; + + /** + * Get the name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name. + * + * @param name the name value to set + * @return the ScriptActionTaskDetails object itself. + */ + public ScriptActionTaskDetails withName(String name) { + this.name = name; + return this; + } + + /** + * Get the path. + * + * @return the path value + */ + public String path() { + return this.path; + } + + /** + * Set the path. + * + * @param path the path value to set + * @return the ScriptActionTaskDetails object itself. + */ + public ScriptActionTaskDetails withPath(String path) { + this.path = path; + return this; + } + + /** + * Get the output. + * + * @return the output value + */ + public String output() { + return this.output; + } + + /** + * Set the output. + * + * @param output the output value to set + * @return the ScriptActionTaskDetails object itself. + */ + public ScriptActionTaskDetails withOutput(String output) { + this.output = output; + return this; + } + + /** + * Get a value indicating whether it is a primary side script or not. + * + * @return the isPrimarySideScript value + */ + public Boolean isPrimarySideScript() { + return this.isPrimarySideScript; + } + + /** + * Set a value indicating whether it is a primary side script or not. + * + * @param isPrimarySideScript the isPrimarySideScript value to set + * @return the ScriptActionTaskDetails object itself. + */ + public ScriptActionTaskDetails withIsPrimarySideScript(Boolean isPrimarySideScript) { + this.isPrimarySideScript = isPrimarySideScript; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ServiceError.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ServiceError.java new file mode 100644 index 0000000000000..db4b5a732ac20 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/ServiceError.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * ASR error model. + */ +public class ServiceError { + /** + * Error code. + */ + @JsonProperty(value = "code") + private String code; + + /** + * Error message. + */ + @JsonProperty(value = "message") + private String message; + + /** + * Possible causes of error. + */ + @JsonProperty(value = "possibleCauses") + private String possibleCauses; + + /** + * Recommended action to resolve error. + */ + @JsonProperty(value = "recommendedAction") + private String recommendedAction; + + /** + * Activity Id. + */ + @JsonProperty(value = "activityId") + private String activityId; + + /** + * Get error code. + * + * @return the code value + */ + public String code() { + return this.code; + } + + /** + * Set error code. + * + * @param code the code value to set + * @return the ServiceError object itself. + */ + public ServiceError withCode(String code) { + this.code = code; + return this; + } + + /** + * Get error message. + * + * @return the message value + */ + public String message() { + return this.message; + } + + /** + * Set error message. + * + * @param message the message value to set + * @return the ServiceError object itself. + */ + public ServiceError withMessage(String message) { + this.message = message; + return this; + } + + /** + * Get possible causes of error. + * + * @return the possibleCauses value + */ + public String possibleCauses() { + return this.possibleCauses; + } + + /** + * Set possible causes of error. + * + * @param possibleCauses the possibleCauses value to set + * @return the ServiceError object itself. + */ + public ServiceError withPossibleCauses(String possibleCauses) { + this.possibleCauses = possibleCauses; + return this; + } + + /** + * Get recommended action to resolve error. + * + * @return the recommendedAction value + */ + public String recommendedAction() { + return this.recommendedAction; + } + + /** + * Set recommended action to resolve error. + * + * @param recommendedAction the recommendedAction value to set + * @return the ServiceError object itself. + */ + public ServiceError withRecommendedAction(String recommendedAction) { + this.recommendedAction = recommendedAction; + return this; + } + + /** + * Get activity Id. + * + * @return the activityId value + */ + public String activityId() { + return this.activityId; + } + + /** + * Set activity Id. + * + * @param activityId the activityId value to set + * @return the ServiceError object itself. + */ + public ServiceError withActivityId(String activityId) { + this.activityId = activityId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SetMultiVmSyncStatus.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SetMultiVmSyncStatus.java new file mode 100644 index 0000000000000..57a315be06144 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SetMultiVmSyncStatus.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for SetMultiVmSyncStatus. + */ +public final class SetMultiVmSyncStatus extends ExpandableStringEnum { + /** Static value Enable for SetMultiVmSyncStatus. */ + public static final SetMultiVmSyncStatus ENABLE = fromString("Enable"); + + /** Static value Disable for SetMultiVmSyncStatus. */ + public static final SetMultiVmSyncStatus DISABLE = fromString("Disable"); + + /** + * Creates or finds a SetMultiVmSyncStatus from its string representation. + * @param name a name to look for + * @return the corresponding SetMultiVmSyncStatus + */ + @JsonCreator + public static SetMultiVmSyncStatus fromString(String name) { + return fromString(name, SetMultiVmSyncStatus.class); + } + + /** + * @return known SetMultiVmSyncStatus values + */ + public static Collection values() { + return values(SetMultiVmSyncStatus.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Severity.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Severity.java new file mode 100644 index 0000000000000..a36d0a1040d66 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Severity.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for Severity. + */ +public final class Severity extends ExpandableStringEnum { + /** Static value NONE for Severity. */ + public static final Severity NONE = fromString("NONE"); + + /** Static value Warning for Severity. */ + public static final Severity WARNING = fromString("Warning"); + + /** Static value Error for Severity. */ + public static final Severity ERROR = fromString("Error"); + + /** Static value Info for Severity. */ + public static final Severity INFO = fromString("Info"); + + /** + * Creates or finds a Severity from its string representation. + * @param name a name to look for + * @return the corresponding Severity + */ + @JsonCreator + public static Severity fromString(String name) { + return fromString(name, Severity.class); + } + + /** + * @return known Severity values + */ + public static Collection values() { + return values(Severity.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SourceSiteOperations.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SourceSiteOperations.java new file mode 100644 index 0000000000000..327651592c168 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SourceSiteOperations.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for SourceSiteOperations. + */ +public final class SourceSiteOperations extends ExpandableStringEnum { + /** Static value Required for SourceSiteOperations. */ + public static final SourceSiteOperations REQUIRED = fromString("Required"); + + /** Static value NotRequired for SourceSiteOperations. */ + public static final SourceSiteOperations NOT_REQUIRED = fromString("NotRequired"); + + /** + * Creates or finds a SourceSiteOperations from its string representation. + * @param name a name to look for + * @return the corresponding SourceSiteOperations + */ + @JsonCreator + public static SourceSiteOperations fromString(String name) { + return fromString(name, SourceSiteOperations.class); + } + + /** + * @return known SourceSiteOperations values + */ + public static Collection values() { + return values(SourceSiteOperations.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassification.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassification.java new file mode 100644 index 0000000000000..503e53308161c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassification.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.StorageClassificationInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing StorageClassification. + */ +public interface StorageClassification extends HasInner, Indexable, Refreshable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + StorageClassificationProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMapping.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMapping.java new file mode 100644 index 0000000000000..3e7f612e33339 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMapping.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.StorageClassificationMappingInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing StorageClassificationMapping. + */ +public interface StorageClassificationMapping extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + StorageClassificationMappingProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the StorageClassificationMapping definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithReplicationStorageClassification, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of StorageClassificationMapping definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a StorageClassificationMapping definition. + */ + interface Blank extends WithReplicationStorageClassification { + } + + /** + * The stage of the storageclassificationmapping definition allowing to specify ReplicationStorageClassification. + */ + interface WithReplicationStorageClassification { + /** + * Specifies fabricName, storageClassificationName. + * @param fabricName Fabric name + * @param storageClassificationName Storage classification name + * @return the next definition stage + */ + WithProperties withExistingReplicationStorageClassification(String fabricName, String storageClassificationName); + } + + /** + * The stage of the storageclassificationmapping definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Storage mapping input properties + * @return the next definition stage + */ + WithCreate withProperties(StorageMappingInputProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a StorageClassificationMapping update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of StorageClassificationMapping update stages. + */ + interface UpdateStages { + /** + * The stage of the storageclassificationmapping update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties Storage mapping input properties + * @return the next update stage + */ + Update withProperties(StorageMappingInputProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMappingInput.java new file mode 100644 index 0000000000000..d4fbb78d88e0e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMappingInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Storage mapping input. + */ +public class StorageClassificationMappingInput { + /** + * Storage mapping input properties. + */ + @JsonProperty(value = "properties") + private StorageMappingInputProperties properties; + + /** + * Get storage mapping input properties. + * + * @return the properties value + */ + public StorageMappingInputProperties properties() { + return this.properties; + } + + /** + * Set storage mapping input properties. + * + * @param properties the properties value to set + * @return the StorageClassificationMappingInput object itself. + */ + public StorageClassificationMappingInput withProperties(StorageMappingInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMappingProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMappingProperties.java new file mode 100644 index 0000000000000..a02465a5de5a8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationMappingProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Storage mapping properties. + */ +public class StorageClassificationMappingProperties { + /** + * Target storage object Id. + */ + @JsonProperty(value = "targetStorageClassificationId") + private String targetStorageClassificationId; + + /** + * Get target storage object Id. + * + * @return the targetStorageClassificationId value + */ + public String targetStorageClassificationId() { + return this.targetStorageClassificationId; + } + + /** + * Set target storage object Id. + * + * @param targetStorageClassificationId the targetStorageClassificationId value to set + * @return the StorageClassificationMappingProperties object itself. + */ + public StorageClassificationMappingProperties withTargetStorageClassificationId(String targetStorageClassificationId) { + this.targetStorageClassificationId = targetStorageClassificationId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationProperties.java new file mode 100644 index 0000000000000..47e6c4cdc3ba8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageClassificationProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Storage object properties. + */ +public class StorageClassificationProperties { + /** + * Friendly name of the Storage classification. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * Get friendly name of the Storage classification. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set friendly name of the Storage classification. + * + * @param friendlyName the friendlyName value to set + * @return the StorageClassificationProperties object itself. + */ + public StorageClassificationProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageMappingInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageMappingInputProperties.java new file mode 100644 index 0000000000000..fb2a4cbefa0ab --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/StorageMappingInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Storage mapping input properties. + */ +public class StorageMappingInputProperties { + /** + * The ID of the storage object. + */ + @JsonProperty(value = "targetStorageClassificationId") + private String targetStorageClassificationId; + + /** + * Get the ID of the storage object. + * + * @return the targetStorageClassificationId value + */ + public String targetStorageClassificationId() { + return this.targetStorageClassificationId; + } + + /** + * Set the ID of the storage object. + * + * @param targetStorageClassificationId the targetStorageClassificationId value to set + * @return the StorageMappingInputProperties object itself. + */ + public StorageMappingInputProperties withTargetStorageClassificationId(String targetStorageClassificationId) { + this.targetStorageClassificationId = targetStorageClassificationId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Subnet.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Subnet.java new file mode 100644 index 0000000000000..0ca5565a195fd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/Subnet.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Subnets of the network. + */ +public class Subnet { + /** + * The subnet name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The subnet friendly name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The list of addresses for the subnet. + */ + @JsonProperty(value = "addressList") + private List addressList; + + /** + * Get the subnet name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the subnet name. + * + * @param name the name value to set + * @return the Subnet object itself. + */ + public Subnet withName(String name) { + this.name = name; + return this; + } + + /** + * Get the subnet friendly name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the subnet friendly name. + * + * @param friendlyName the friendlyName value to set + * @return the Subnet object itself. + */ + public Subnet withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the list of addresses for the subnet. + * + * @return the addressList value + */ + public List addressList() { + return this.addressList; + } + + /** + * Set the list of addresses for the subnet. + * + * @param addressList the addressList value to set + * @return the Subnet object itself. + */ + public Subnet withAddressList(List addressList) { + this.addressList = addressList; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionInput.java new file mode 100644 index 0000000000000..47f1cb85cd30a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Switch protection input. + */ +public class SwitchProtectionInput { + /** + * Switch protection properties. + */ + @JsonProperty(value = "properties") + private SwitchProtectionInputProperties properties; + + /** + * Get switch protection properties. + * + * @return the properties value + */ + public SwitchProtectionInputProperties properties() { + return this.properties; + } + + /** + * Set switch protection properties. + * + * @param properties the properties value to set + * @return the SwitchProtectionInput object itself. + */ + public SwitchProtectionInput withProperties(SwitchProtectionInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionInputProperties.java new file mode 100644 index 0000000000000..de15678ef45a8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionInputProperties.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Switch protection input properties. + */ +public class SwitchProtectionInputProperties { + /** + * The unique replication protected item name. + */ + @JsonProperty(value = "replicationProtectedItemName") + private String replicationProtectedItemName; + + /** + * Provider specific switch protection input. + */ + @JsonProperty(value = "providerSpecificDetails") + private SwitchProtectionProviderSpecificInput providerSpecificDetails; + + /** + * Get the unique replication protected item name. + * + * @return the replicationProtectedItemName value + */ + public String replicationProtectedItemName() { + return this.replicationProtectedItemName; + } + + /** + * Set the unique replication protected item name. + * + * @param replicationProtectedItemName the replicationProtectedItemName value to set + * @return the SwitchProtectionInputProperties object itself. + */ + public SwitchProtectionInputProperties withReplicationProtectedItemName(String replicationProtectedItemName) { + this.replicationProtectedItemName = replicationProtectedItemName; + return this; + } + + /** + * Get provider specific switch protection input. + * + * @return the providerSpecificDetails value + */ + public SwitchProtectionProviderSpecificInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set provider specific switch protection input. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the SwitchProtectionInputProperties object itself. + */ + public SwitchProtectionInputProperties withProviderSpecificDetails(SwitchProtectionProviderSpecificInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionJobDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionJobDetails.java new file mode 100644 index 0000000000000..ad61ceb3d2f6f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionJobDetails.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents details for switch protection job. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("SwitchProtectionJobDetails") +public class SwitchProtectionJobDetails extends JobDetails { + /** + * ARM Id of the new replication protected item. + */ + @JsonProperty(value = "newReplicationProtectedItemId") + private String newReplicationProtectedItemId; + + /** + * Get aRM Id of the new replication protected item. + * + * @return the newReplicationProtectedItemId value + */ + public String newReplicationProtectedItemId() { + return this.newReplicationProtectedItemId; + } + + /** + * Set aRM Id of the new replication protected item. + * + * @param newReplicationProtectedItemId the newReplicationProtectedItemId value to set + * @return the SwitchProtectionJobDetails object itself. + */ + public SwitchProtectionJobDetails withNewReplicationProtectedItemId(String newReplicationProtectedItemId) { + this.newReplicationProtectedItemId = newReplicationProtectedItemId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionProviderSpecificInput.java new file mode 100644 index 0000000000000..f624855a44089 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/SwitchProtectionProviderSpecificInput.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Provider specific switch protection input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("SwitchProtectionProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2ASwitchProtectionInput.class) +}) +public class SwitchProtectionProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSize.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSize.java new file mode 100644 index 0000000000000..538c40a01e6ca --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSize.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.TargetComputeSizeInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing TargetComputeSize. + */ +public interface TargetComputeSize extends HasInner, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + TargetComputeSizeProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSizeProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSizeProperties.java new file mode 100644 index 0000000000000..ecca6cbd68aef --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSizeProperties.java @@ -0,0 +1,227 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents applicable recovery vm sizes properties. + */ +public class TargetComputeSizeProperties { + /** + * Target compute size name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Target compute size display name. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The maximum cpu cores count supported by target compute size. + */ + @JsonProperty(value = "cpuCoresCount") + private Integer cpuCoresCount; + + /** + * The maximum memory in GB supported by target compute size. + */ + @JsonProperty(value = "memoryInGB") + private Double memoryInGB; + + /** + * The maximum data disks count supported by target compute size. + */ + @JsonProperty(value = "maxDataDiskCount") + private Integer maxDataDiskCount; + + /** + * The maximum Nics count supported by target compute size. + */ + @JsonProperty(value = "maxNicsCount") + private Integer maxNicsCount; + + /** + * The reasons why the target compute size is not applicable for the + * protected item. + */ + @JsonProperty(value = "errors") + private List errors; + + /** + * The value indicating whether the target compute size supports high Iops. + */ + @JsonProperty(value = "highIopsSupported") + private String highIopsSupported; + + /** + * Get target compute size name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set target compute size name. + * + * @param name the name value to set + * @return the TargetComputeSizeProperties object itself. + */ + public TargetComputeSizeProperties withName(String name) { + this.name = name; + return this; + } + + /** + * Get target compute size display name. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set target compute size display name. + * + * @param friendlyName the friendlyName value to set + * @return the TargetComputeSizeProperties object itself. + */ + public TargetComputeSizeProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the maximum cpu cores count supported by target compute size. + * + * @return the cpuCoresCount value + */ + public Integer cpuCoresCount() { + return this.cpuCoresCount; + } + + /** + * Set the maximum cpu cores count supported by target compute size. + * + * @param cpuCoresCount the cpuCoresCount value to set + * @return the TargetComputeSizeProperties object itself. + */ + public TargetComputeSizeProperties withCpuCoresCount(Integer cpuCoresCount) { + this.cpuCoresCount = cpuCoresCount; + return this; + } + + /** + * Get the maximum memory in GB supported by target compute size. + * + * @return the memoryInGB value + */ + public Double memoryInGB() { + return this.memoryInGB; + } + + /** + * Set the maximum memory in GB supported by target compute size. + * + * @param memoryInGB the memoryInGB value to set + * @return the TargetComputeSizeProperties object itself. + */ + public TargetComputeSizeProperties withMemoryInGB(Double memoryInGB) { + this.memoryInGB = memoryInGB; + return this; + } + + /** + * Get the maximum data disks count supported by target compute size. + * + * @return the maxDataDiskCount value + */ + public Integer maxDataDiskCount() { + return this.maxDataDiskCount; + } + + /** + * Set the maximum data disks count supported by target compute size. + * + * @param maxDataDiskCount the maxDataDiskCount value to set + * @return the TargetComputeSizeProperties object itself. + */ + public TargetComputeSizeProperties withMaxDataDiskCount(Integer maxDataDiskCount) { + this.maxDataDiskCount = maxDataDiskCount; + return this; + } + + /** + * Get the maximum Nics count supported by target compute size. + * + * @return the maxNicsCount value + */ + public Integer maxNicsCount() { + return this.maxNicsCount; + } + + /** + * Set the maximum Nics count supported by target compute size. + * + * @param maxNicsCount the maxNicsCount value to set + * @return the TargetComputeSizeProperties object itself. + */ + public TargetComputeSizeProperties withMaxNicsCount(Integer maxNicsCount) { + this.maxNicsCount = maxNicsCount; + return this; + } + + /** + * Get the reasons why the target compute size is not applicable for the protected item. + * + * @return the errors value + */ + public List errors() { + return this.errors; + } + + /** + * Set the reasons why the target compute size is not applicable for the protected item. + * + * @param errors the errors value to set + * @return the TargetComputeSizeProperties object itself. + */ + public TargetComputeSizeProperties withErrors(List errors) { + this.errors = errors; + return this; + } + + /** + * Get the value indicating whether the target compute size supports high Iops. + * + * @return the highIopsSupported value + */ + public String highIopsSupported() { + return this.highIopsSupported; + } + + /** + * Set the value indicating whether the target compute size supports high Iops. + * + * @param highIopsSupported the highIopsSupported value to set + * @return the TargetComputeSizeProperties object itself. + */ + public TargetComputeSizeProperties withHighIopsSupported(String highIopsSupported) { + this.highIopsSupported = highIopsSupported; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSizes.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSizes.java new file mode 100644 index 0000000000000..e28364d575779 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TargetComputeSizes.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.TargetComputeSizesInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing TargetComputeSizes. + */ +public interface TargetComputeSizes extends HasInner { + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByReplicationProtectedItemsAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TaskTypeDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TaskTypeDetails.java new file mode 100644 index 0000000000000..38efd8e14395b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TaskTypeDetails.java @@ -0,0 +1,31 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Task details based on specific task type. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("TaskTypeDetails") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "AutomationRunbookTaskDetails", value = AutomationRunbookTaskDetails.class), + @JsonSubTypes.Type(name = "ConsistencyCheckTaskDetails", value = ConsistencyCheckTaskDetails.class), + @JsonSubTypes.Type(name = "FabricReplicationGroupTaskDetails", value = FabricReplicationGroupTaskDetails.class), + @JsonSubTypes.Type(name = "JobTaskDetails", value = JobTaskDetails.class), + @JsonSubTypes.Type(name = "ManualActionTaskDetails", value = ManualActionTaskDetails.class), + @JsonSubTypes.Type(name = "ScriptActionTaskDetails", value = ScriptActionTaskDetails.class), + @JsonSubTypes.Type(name = "VirtualMachineTaskDetails", value = VirtualMachineTaskDetails.class), + @JsonSubTypes.Type(name = "VmNicUpdatesTaskDetails", value = VmNicUpdatesTaskDetails.class) +}) +public class TaskTypeDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverCleanupInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverCleanupInput.java new file mode 100644 index 0000000000000..fa0b5d80102f6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverCleanupInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input definition for test failover cleanup. + */ +public class TestFailoverCleanupInput { + /** + * Test failover cleanup input properties. + */ + @JsonProperty(value = "properties", required = true) + private TestFailoverCleanupInputProperties properties; + + /** + * Get test failover cleanup input properties. + * + * @return the properties value + */ + public TestFailoverCleanupInputProperties properties() { + return this.properties; + } + + /** + * Set test failover cleanup input properties. + * + * @param properties the properties value to set + * @return the TestFailoverCleanupInput object itself. + */ + public TestFailoverCleanupInput withProperties(TestFailoverCleanupInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverCleanupInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverCleanupInputProperties.java new file mode 100644 index 0000000000000..836093bdea4bb --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverCleanupInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input definition for test failover cleanup input properties. + */ +public class TestFailoverCleanupInputProperties { + /** + * Test failover cleanup comments. + */ + @JsonProperty(value = "comments") + private String comments; + + /** + * Get test failover cleanup comments. + * + * @return the comments value + */ + public String comments() { + return this.comments; + } + + /** + * Set test failover cleanup comments. + * + * @param comments the comments value to set + * @return the TestFailoverCleanupInputProperties object itself. + */ + public TestFailoverCleanupInputProperties withComments(String comments) { + this.comments = comments; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverInput.java new file mode 100644 index 0000000000000..54a43100bcd7f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input definition for planned failover. + */ +public class TestFailoverInput { + /** + * Planned failover input properties. + */ + @JsonProperty(value = "properties") + private TestFailoverInputProperties properties; + + /** + * Get planned failover input properties. + * + * @return the properties value + */ + public TestFailoverInputProperties properties() { + return this.properties; + } + + /** + * Set planned failover input properties. + * + * @param properties the properties value to set + * @return the TestFailoverInput object itself. + */ + public TestFailoverInput withProperties(TestFailoverInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverInputProperties.java new file mode 100644 index 0000000000000..a1001040c4ee7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverInputProperties.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input definition for planned failover input properties. + */ +public class TestFailoverInputProperties { + /** + * Failover direction. + */ + @JsonProperty(value = "failoverDirection") + private String failoverDirection; + + /** + * Network type to be used for test failover. + */ + @JsonProperty(value = "networkType") + private String networkType; + + /** + * The id of the network to be used for test failover. + */ + @JsonProperty(value = "networkId") + private String networkId; + + /** + * A value indicating whether the test failover cleanup is to be skipped. + */ + @JsonProperty(value = "skipTestFailoverCleanup") + private String skipTestFailoverCleanup; + + /** + * Provider specific settings. + */ + @JsonProperty(value = "providerSpecificDetails") + private ProviderSpecificFailoverInput providerSpecificDetails; + + /** + * Get failover direction. + * + * @return the failoverDirection value + */ + public String failoverDirection() { + return this.failoverDirection; + } + + /** + * Set failover direction. + * + * @param failoverDirection the failoverDirection value to set + * @return the TestFailoverInputProperties object itself. + */ + public TestFailoverInputProperties withFailoverDirection(String failoverDirection) { + this.failoverDirection = failoverDirection; + return this; + } + + /** + * Get network type to be used for test failover. + * + * @return the networkType value + */ + public String networkType() { + return this.networkType; + } + + /** + * Set network type to be used for test failover. + * + * @param networkType the networkType value to set + * @return the TestFailoverInputProperties object itself. + */ + public TestFailoverInputProperties withNetworkType(String networkType) { + this.networkType = networkType; + return this; + } + + /** + * Get the id of the network to be used for test failover. + * + * @return the networkId value + */ + public String networkId() { + return this.networkId; + } + + /** + * Set the id of the network to be used for test failover. + * + * @param networkId the networkId value to set + * @return the TestFailoverInputProperties object itself. + */ + public TestFailoverInputProperties withNetworkId(String networkId) { + this.networkId = networkId; + return this; + } + + /** + * Get a value indicating whether the test failover cleanup is to be skipped. + * + * @return the skipTestFailoverCleanup value + */ + public String skipTestFailoverCleanup() { + return this.skipTestFailoverCleanup; + } + + /** + * Set a value indicating whether the test failover cleanup is to be skipped. + * + * @param skipTestFailoverCleanup the skipTestFailoverCleanup value to set + * @return the TestFailoverInputProperties object itself. + */ + public TestFailoverInputProperties withSkipTestFailoverCleanup(String skipTestFailoverCleanup) { + this.skipTestFailoverCleanup = skipTestFailoverCleanup; + return this; + } + + /** + * Get provider specific settings. + * + * @return the providerSpecificDetails value + */ + public ProviderSpecificFailoverInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set provider specific settings. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the TestFailoverInputProperties object itself. + */ + public TestFailoverInputProperties withProviderSpecificDetails(ProviderSpecificFailoverInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverJobDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverJobDetails.java new file mode 100644 index 0000000000000..4258ebd5c3602 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestFailoverJobDetails.java @@ -0,0 +1,178 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the details for a test failover job. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("TestFailoverJobDetails") +public class TestFailoverJobDetails extends JobDetails { + /** + * The test failover status. + */ + @JsonProperty(value = "testFailoverStatus") + private String testFailoverStatus; + + /** + * The test failover comments. + */ + @JsonProperty(value = "comments") + private String comments; + + /** + * The test network name. + */ + @JsonProperty(value = "networkName") + private String networkName; + + /** + * The test network friendly name. + */ + @JsonProperty(value = "networkFriendlyName") + private String networkFriendlyName; + + /** + * The test network type (see TestFailoverInput enum for possible values). + */ + @JsonProperty(value = "networkType") + private String networkType; + + /** + * The test VM details. + */ + @JsonProperty(value = "protectedItemDetails") + private List protectedItemDetails; + + /** + * Get the test failover status. + * + * @return the testFailoverStatus value + */ + public String testFailoverStatus() { + return this.testFailoverStatus; + } + + /** + * Set the test failover status. + * + * @param testFailoverStatus the testFailoverStatus value to set + * @return the TestFailoverJobDetails object itself. + */ + public TestFailoverJobDetails withTestFailoverStatus(String testFailoverStatus) { + this.testFailoverStatus = testFailoverStatus; + return this; + } + + /** + * Get the test failover comments. + * + * @return the comments value + */ + public String comments() { + return this.comments; + } + + /** + * Set the test failover comments. + * + * @param comments the comments value to set + * @return the TestFailoverJobDetails object itself. + */ + public TestFailoverJobDetails withComments(String comments) { + this.comments = comments; + return this; + } + + /** + * Get the test network name. + * + * @return the networkName value + */ + public String networkName() { + return this.networkName; + } + + /** + * Set the test network name. + * + * @param networkName the networkName value to set + * @return the TestFailoverJobDetails object itself. + */ + public TestFailoverJobDetails withNetworkName(String networkName) { + this.networkName = networkName; + return this; + } + + /** + * Get the test network friendly name. + * + * @return the networkFriendlyName value + */ + public String networkFriendlyName() { + return this.networkFriendlyName; + } + + /** + * Set the test network friendly name. + * + * @param networkFriendlyName the networkFriendlyName value to set + * @return the TestFailoverJobDetails object itself. + */ + public TestFailoverJobDetails withNetworkFriendlyName(String networkFriendlyName) { + this.networkFriendlyName = networkFriendlyName; + return this; + } + + /** + * Get the test network type (see TestFailoverInput enum for possible values). + * + * @return the networkType value + */ + public String networkType() { + return this.networkType; + } + + /** + * Set the test network type (see TestFailoverInput enum for possible values). + * + * @param networkType the networkType value to set + * @return the TestFailoverJobDetails object itself. + */ + public TestFailoverJobDetails withNetworkType(String networkType) { + this.networkType = networkType; + return this; + } + + /** + * Get the test VM details. + * + * @return the protectedItemDetails value + */ + public List protectedItemDetails() { + return this.protectedItemDetails; + } + + /** + * Set the test VM details. + * + * @param protectedItemDetails the protectedItemDetails value to set + * @return the TestFailoverJobDetails object itself. + */ + public TestFailoverJobDetails withProtectedItemDetails(List protectedItemDetails) { + this.protectedItemDetails = protectedItemDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateCleanupInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateCleanupInput.java new file mode 100644 index 0000000000000..f19aeec944aac --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateCleanupInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input for test migrate cleanup. + */ +public class TestMigrateCleanupInput { + /** + * Test migrate cleanup input properties. + */ + @JsonProperty(value = "properties", required = true) + private TestMigrateCleanupInputProperties properties; + + /** + * Get test migrate cleanup input properties. + * + * @return the properties value + */ + public TestMigrateCleanupInputProperties properties() { + return this.properties; + } + + /** + * Set test migrate cleanup input properties. + * + * @param properties the properties value to set + * @return the TestMigrateCleanupInput object itself. + */ + public TestMigrateCleanupInput withProperties(TestMigrateCleanupInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateCleanupInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateCleanupInputProperties.java new file mode 100644 index 0000000000000..c88b3cdd38a07 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateCleanupInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Test migrate cleanup input properties. + */ +public class TestMigrateCleanupInputProperties { + /** + * Test migrate cleanup comments. + */ + @JsonProperty(value = "comments") + private String comments; + + /** + * Get test migrate cleanup comments. + * + * @return the comments value + */ + public String comments() { + return this.comments; + } + + /** + * Set test migrate cleanup comments. + * + * @param comments the comments value to set + * @return the TestMigrateCleanupInputProperties object itself. + */ + public TestMigrateCleanupInputProperties withComments(String comments) { + this.comments = comments; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateInput.java new file mode 100644 index 0000000000000..25dd86f674f11 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input for test migrate. + */ +public class TestMigrateInput { + /** + * Test migrate input properties. + */ + @JsonProperty(value = "properties", required = true) + private TestMigrateInputProperties properties; + + /** + * Get test migrate input properties. + * + * @return the properties value + */ + public TestMigrateInputProperties properties() { + return this.properties; + } + + /** + * Set test migrate input properties. + * + * @param properties the properties value to set + * @return the TestMigrateInput object itself. + */ + public TestMigrateInput withProperties(TestMigrateInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateInputProperties.java new file mode 100644 index 0000000000000..20548a3fb09a0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Test migrate input properties. + */ +public class TestMigrateInputProperties { + /** + * The provider specific details. + */ + @JsonProperty(value = "providerSpecificDetails", required = true) + private TestMigrateProviderSpecificInput providerSpecificDetails; + + /** + * Get the provider specific details. + * + * @return the providerSpecificDetails value + */ + public TestMigrateProviderSpecificInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific details. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the TestMigrateInputProperties object itself. + */ + public TestMigrateInputProperties withProviderSpecificDetails(TestMigrateProviderSpecificInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateProviderSpecificInput.java new file mode 100644 index 0000000000000..b5148dd14523e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrateProviderSpecificInput.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Test migrate provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("TestMigrateProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "VMwareCbt", value = VMwareCbtTestMigrateInput.class) +}) +public class TestMigrateProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrationState.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrationState.java new file mode 100644 index 0000000000000..80549233bc5ad --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/TestMigrationState.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for TestMigrationState. + */ +public final class TestMigrationState extends ExpandableStringEnum { + /** Static value None for TestMigrationState. */ + public static final TestMigrationState NONE = fromString("None"); + + /** Static value TestMigrationInProgress for TestMigrationState. */ + public static final TestMigrationState TEST_MIGRATION_IN_PROGRESS = fromString("TestMigrationInProgress"); + + /** Static value TestMigrationSucceeded for TestMigrationState. */ + public static final TestMigrationState TEST_MIGRATION_SUCCEEDED = fromString("TestMigrationSucceeded"); + + /** Static value TestMigrationFailed for TestMigrationState. */ + public static final TestMigrationState TEST_MIGRATION_FAILED = fromString("TestMigrationFailed"); + + /** Static value TestMigrationCleanupInProgress for TestMigrationState. */ + public static final TestMigrationState TEST_MIGRATION_CLEANUP_IN_PROGRESS = fromString("TestMigrationCleanupInProgress"); + + /** + * Creates or finds a TestMigrationState from its string representation. + * @param name a name to look for + * @return the corresponding TestMigrationState + */ + @JsonCreator + public static TestMigrationState fromString(String name) { + return fromString(name, TestMigrationState.class); + } + + /** + * @return known TestMigrationState values + */ + public static Collection values() { + return values(TestMigrationState.class); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UnplannedFailoverInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UnplannedFailoverInput.java new file mode 100644 index 0000000000000..34b3ad32147ad --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UnplannedFailoverInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input definition for planned failover. + */ +public class UnplannedFailoverInput { + /** + * Planned failover input properties. + */ + @JsonProperty(value = "properties") + private UnplannedFailoverInputProperties properties; + + /** + * Get planned failover input properties. + * + * @return the properties value + */ + public UnplannedFailoverInputProperties properties() { + return this.properties; + } + + /** + * Set planned failover input properties. + * + * @param properties the properties value to set + * @return the UnplannedFailoverInput object itself. + */ + public UnplannedFailoverInput withProperties(UnplannedFailoverInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UnplannedFailoverInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UnplannedFailoverInputProperties.java new file mode 100644 index 0000000000000..083297936c6fe --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UnplannedFailoverInputProperties.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input definition for planned failover input properties. + */ +public class UnplannedFailoverInputProperties { + /** + * Failover direction. + */ + @JsonProperty(value = "failoverDirection") + private String failoverDirection; + + /** + * Source site operations status. + */ + @JsonProperty(value = "sourceSiteOperations") + private String sourceSiteOperations; + + /** + * Provider specific settings. + */ + @JsonProperty(value = "providerSpecificDetails") + private ProviderSpecificFailoverInput providerSpecificDetails; + + /** + * Get failover direction. + * + * @return the failoverDirection value + */ + public String failoverDirection() { + return this.failoverDirection; + } + + /** + * Set failover direction. + * + * @param failoverDirection the failoverDirection value to set + * @return the UnplannedFailoverInputProperties object itself. + */ + public UnplannedFailoverInputProperties withFailoverDirection(String failoverDirection) { + this.failoverDirection = failoverDirection; + return this; + } + + /** + * Get source site operations status. + * + * @return the sourceSiteOperations value + */ + public String sourceSiteOperations() { + return this.sourceSiteOperations; + } + + /** + * Set source site operations status. + * + * @param sourceSiteOperations the sourceSiteOperations value to set + * @return the UnplannedFailoverInputProperties object itself. + */ + public UnplannedFailoverInputProperties withSourceSiteOperations(String sourceSiteOperations) { + this.sourceSiteOperations = sourceSiteOperations; + return this; + } + + /** + * Get provider specific settings. + * + * @return the providerSpecificDetails value + */ + public ProviderSpecificFailoverInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set provider specific settings. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the UnplannedFailoverInputProperties object itself. + */ + public UnplannedFailoverInputProperties withProviderSpecificDetails(ProviderSpecificFailoverInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInput.java new file mode 100644 index 0000000000000..cdfa467fbc02e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Update migration item input. + */ +public class UpdateMigrationItemInput { + /** + * Update migration item input properties. + */ + @JsonProperty(value = "properties") + private UpdateMigrationItemInputProperties properties; + + /** + * Get update migration item input properties. + * + * @return the properties value + */ + public UpdateMigrationItemInputProperties properties() { + return this.properties; + } + + /** + * Set update migration item input properties. + * + * @param properties the properties value to set + * @return the UpdateMigrationItemInput object itself. + */ + public UpdateMigrationItemInput withProperties(UpdateMigrationItemInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInputProperties.java new file mode 100644 index 0000000000000..80ae4968b01da --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Update migration item input properties. + */ +public class UpdateMigrationItemInputProperties { + /** + * The provider specific input to update migration item. + */ + @JsonProperty(value = "providerSpecificDetails", required = true) + private UpdateMigrationItemProviderSpecificInput providerSpecificDetails; + + /** + * Get the provider specific input to update migration item. + * + * @return the providerSpecificDetails value + */ + public UpdateMigrationItemProviderSpecificInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific input to update migration item. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the UpdateMigrationItemInputProperties object itself. + */ + public UpdateMigrationItemInputProperties withProviderSpecificDetails(UpdateMigrationItemProviderSpecificInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemProviderSpecificInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemProviderSpecificInput.java new file mode 100644 index 0000000000000..004d411271c1a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMigrationItemProviderSpecificInput.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Update migration item provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("UpdateMigrationItemProviderSpecificInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "VMwareCbt", value = VMwareCbtUpdateMigrationItemInput.class) +}) +public class UpdateMigrationItemProviderSpecificInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMobilityServiceRequest.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMobilityServiceRequest.java new file mode 100644 index 0000000000000..4f28e40563236 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMobilityServiceRequest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Request to update the mobility service on a protected item. + */ +public class UpdateMobilityServiceRequest { + /** + * The properties of the update mobility service request. + */ + @JsonProperty(value = "properties") + private UpdateMobilityServiceRequestProperties properties; + + /** + * Get the properties of the update mobility service request. + * + * @return the properties value + */ + public UpdateMobilityServiceRequestProperties properties() { + return this.properties; + } + + /** + * Set the properties of the update mobility service request. + * + * @param properties the properties value to set + * @return the UpdateMobilityServiceRequest object itself. + */ + public UpdateMobilityServiceRequest withProperties(UpdateMobilityServiceRequestProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMobilityServiceRequestProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMobilityServiceRequestProperties.java new file mode 100644 index 0000000000000..651b56b208169 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateMobilityServiceRequestProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The properties of an update mobility service request. + */ +public class UpdateMobilityServiceRequestProperties { + /** + * The CS run as account Id. + */ + @JsonProperty(value = "runAsAccountId") + private String runAsAccountId; + + /** + * Get the CS run as account Id. + * + * @return the runAsAccountId value + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Set the CS run as account Id. + * + * @param runAsAccountId the runAsAccountId value to set + * @return the UpdateMobilityServiceRequestProperties object itself. + */ + public UpdateMobilityServiceRequestProperties withRunAsAccountId(String runAsAccountId) { + this.runAsAccountId = runAsAccountId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateNetworkMappingInput.java new file mode 100644 index 0000000000000..b902340f7a35b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateNetworkMappingInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Update network mapping input. + */ +public class UpdateNetworkMappingInput { + /** + * The input properties needed to update network mapping. + */ + @JsonProperty(value = "properties") + private UpdateNetworkMappingInputProperties properties; + + /** + * Get the input properties needed to update network mapping. + * + * @return the properties value + */ + public UpdateNetworkMappingInputProperties properties() { + return this.properties; + } + + /** + * Set the input properties needed to update network mapping. + * + * @param properties the properties value to set + * @return the UpdateNetworkMappingInput object itself. + */ + public UpdateNetworkMappingInput withProperties(UpdateNetworkMappingInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateNetworkMappingInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateNetworkMappingInputProperties.java new file mode 100644 index 0000000000000..609be0c965500 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateNetworkMappingInputProperties.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Common input details for network mapping operation. + */ +public class UpdateNetworkMappingInputProperties { + /** + * Recovery fabric name. + */ + @JsonProperty(value = "recoveryFabricName") + private String recoveryFabricName; + + /** + * Recovery network Id. + */ + @JsonProperty(value = "recoveryNetworkId") + private String recoveryNetworkId; + + /** + * Fabrics specific input network Id. + */ + @JsonProperty(value = "fabricSpecificDetails") + private FabricSpecificUpdateNetworkMappingInput fabricSpecificDetails; + + /** + * Get recovery fabric name. + * + * @return the recoveryFabricName value + */ + public String recoveryFabricName() { + return this.recoveryFabricName; + } + + /** + * Set recovery fabric name. + * + * @param recoveryFabricName the recoveryFabricName value to set + * @return the UpdateNetworkMappingInputProperties object itself. + */ + public UpdateNetworkMappingInputProperties withRecoveryFabricName(String recoveryFabricName) { + this.recoveryFabricName = recoveryFabricName; + return this; + } + + /** + * Get recovery network Id. + * + * @return the recoveryNetworkId value + */ + public String recoveryNetworkId() { + return this.recoveryNetworkId; + } + + /** + * Set recovery network Id. + * + * @param recoveryNetworkId the recoveryNetworkId value to set + * @return the UpdateNetworkMappingInputProperties object itself. + */ + public UpdateNetworkMappingInputProperties withRecoveryNetworkId(String recoveryNetworkId) { + this.recoveryNetworkId = recoveryNetworkId; + return this; + } + + /** + * Get fabrics specific input network Id. + * + * @return the fabricSpecificDetails value + */ + public FabricSpecificUpdateNetworkMappingInput fabricSpecificDetails() { + return this.fabricSpecificDetails; + } + + /** + * Set fabrics specific input network Id. + * + * @param fabricSpecificDetails the fabricSpecificDetails value to set + * @return the UpdateNetworkMappingInputProperties object itself. + */ + public UpdateNetworkMappingInputProperties withFabricSpecificDetails(FabricSpecificUpdateNetworkMappingInput fabricSpecificDetails) { + this.fabricSpecificDetails = fabricSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdatePolicyInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdatePolicyInput.java new file mode 100644 index 0000000000000..bce67c17ceb6b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdatePolicyInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Update policy input. + */ +public class UpdatePolicyInput { + /** + * The ReplicationProviderSettings. + */ + @JsonProperty(value = "properties") + private UpdatePolicyInputProperties properties; + + /** + * Get the ReplicationProviderSettings. + * + * @return the properties value + */ + public UpdatePolicyInputProperties properties() { + return this.properties; + } + + /** + * Set the ReplicationProviderSettings. + * + * @param properties the properties value to set + * @return the UpdatePolicyInput object itself. + */ + public UpdatePolicyInput withProperties(UpdatePolicyInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdatePolicyInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdatePolicyInputProperties.java new file mode 100644 index 0000000000000..8877d402943aa --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdatePolicyInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy update properties. + */ +public class UpdatePolicyInputProperties { + /** + * The ReplicationProviderSettings. + */ + @JsonProperty(value = "replicationProviderSettings") + private PolicyProviderSpecificInput replicationProviderSettings; + + /** + * Get the ReplicationProviderSettings. + * + * @return the replicationProviderSettings value + */ + public PolicyProviderSpecificInput replicationProviderSettings() { + return this.replicationProviderSettings; + } + + /** + * Set the ReplicationProviderSettings. + * + * @param replicationProviderSettings the replicationProviderSettings value to set + * @return the UpdatePolicyInputProperties object itself. + */ + public UpdatePolicyInputProperties withReplicationProviderSettings(PolicyProviderSpecificInput replicationProviderSettings) { + this.replicationProviderSettings = replicationProviderSettings; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateProtectionContainerMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateProtectionContainerMappingInput.java new file mode 100644 index 0000000000000..095ff6cff91e3 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateProtectionContainerMappingInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Container pairing update input. + */ +public class UpdateProtectionContainerMappingInput { + /** + * Update protection container mapping input properties. + */ + @JsonProperty(value = "properties") + private UpdateProtectionContainerMappingInputProperties properties; + + /** + * Get update protection container mapping input properties. + * + * @return the properties value + */ + public UpdateProtectionContainerMappingInputProperties properties() { + return this.properties; + } + + /** + * Set update protection container mapping input properties. + * + * @param properties the properties value to set + * @return the UpdateProtectionContainerMappingInput object itself. + */ + public UpdateProtectionContainerMappingInput withProperties(UpdateProtectionContainerMappingInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateProtectionContainerMappingInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateProtectionContainerMappingInputProperties.java new file mode 100644 index 0000000000000..96cedcb25629c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateProtectionContainerMappingInputProperties.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Container pairing update input. + */ +public class UpdateProtectionContainerMappingInputProperties { + /** + * Provider specific input for updating protection container mapping. + */ + @JsonProperty(value = "providerSpecificInput") + private ReplicationProviderSpecificUpdateContainerMappingInput providerSpecificInput; + + /** + * Get provider specific input for updating protection container mapping. + * + * @return the providerSpecificInput value + */ + public ReplicationProviderSpecificUpdateContainerMappingInput providerSpecificInput() { + return this.providerSpecificInput; + } + + /** + * Set provider specific input for updating protection container mapping. + * + * @param providerSpecificInput the providerSpecificInput value to set + * @return the UpdateProtectionContainerMappingInputProperties object itself. + */ + public UpdateProtectionContainerMappingInputProperties withProviderSpecificInput(ReplicationProviderSpecificUpdateContainerMappingInput providerSpecificInput) { + this.providerSpecificInput = providerSpecificInput; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateRecoveryPlanInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateRecoveryPlanInput.java new file mode 100644 index 0000000000000..c53652bfd1648 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateRecoveryPlanInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Update recovery plan input class. + */ +public class UpdateRecoveryPlanInput { + /** + * Recovery plan update properties. + */ + @JsonProperty(value = "properties") + private UpdateRecoveryPlanInputProperties properties; + + /** + * Get recovery plan update properties. + * + * @return the properties value + */ + public UpdateRecoveryPlanInputProperties properties() { + return this.properties; + } + + /** + * Set recovery plan update properties. + * + * @param properties the properties value to set + * @return the UpdateRecoveryPlanInput object itself. + */ + public UpdateRecoveryPlanInput withProperties(UpdateRecoveryPlanInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateRecoveryPlanInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateRecoveryPlanInputProperties.java new file mode 100644 index 0000000000000..588eac2b191fa --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateRecoveryPlanInputProperties.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Recovery plan update properties. + */ +public class UpdateRecoveryPlanInputProperties { + /** + * The recovery plan groups. + */ + @JsonProperty(value = "groups") + private List groups; + + /** + * Get the recovery plan groups. + * + * @return the groups value + */ + public List groups() { + return this.groups; + } + + /** + * Set the recovery plan groups. + * + * @param groups the groups value to set + * @return the UpdateRecoveryPlanInputProperties object itself. + */ + public UpdateRecoveryPlanInputProperties withGroups(List groups) { + this.groups = groups; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemInput.java new file mode 100644 index 0000000000000..37987e917a104 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemInput.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Update replication protected item input. + */ +public class UpdateReplicationProtectedItemInput { + /** + * Update replication protected item properties. + */ + @JsonProperty(value = "properties") + private UpdateReplicationProtectedItemInputProperties properties; + + /** + * Get update replication protected item properties. + * + * @return the properties value + */ + public UpdateReplicationProtectedItemInputProperties properties() { + return this.properties; + } + + /** + * Set update replication protected item properties. + * + * @param properties the properties value to set + * @return the UpdateReplicationProtectedItemInput object itself. + */ + public UpdateReplicationProtectedItemInput withProperties(UpdateReplicationProtectedItemInputProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemInputProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemInputProperties.java new file mode 100644 index 0000000000000..95ecbb8c876b8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemInputProperties.java @@ -0,0 +1,255 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Update protected item input properties. + */ +public class UpdateReplicationProtectedItemInputProperties { + /** + * Target azure VM name given by the user. + */ + @JsonProperty(value = "recoveryAzureVMName") + private String recoveryAzureVMName; + + /** + * Target Azure Vm size. + */ + @JsonProperty(value = "recoveryAzureVMSize") + private String recoveryAzureVMSize; + + /** + * Target Azure Network Id. + */ + @JsonProperty(value = "selectedRecoveryAzureNetworkId") + private String selectedRecoveryAzureNetworkId; + + /** + * The selected source nic Id which will be used as the primary nic during + * failover. + */ + @JsonProperty(value = "selectedSourceNicId") + private String selectedSourceNicId; + + /** + * The selected option to enable RDP\SSH on target vm after failover. + * String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + */ + @JsonProperty(value = "enableRdpOnTargetOption") + private String enableRdpOnTargetOption; + + /** + * The list of vm nic details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * License type. Possible values include: 'NotSpecified', 'NoLicenseType', + * 'WindowsServer'. + */ + @JsonProperty(value = "licenseType") + private LicenseType licenseType; + + /** + * The target availability set id. + */ + @JsonProperty(value = "recoveryAvailabilitySetId") + private String recoveryAvailabilitySetId; + + /** + * The provider specific input to update replication protected item. + */ + @JsonProperty(value = "providerSpecificDetails") + private UpdateReplicationProtectedItemProviderInput providerSpecificDetails; + + /** + * Get target azure VM name given by the user. + * + * @return the recoveryAzureVMName value + */ + public String recoveryAzureVMName() { + return this.recoveryAzureVMName; + } + + /** + * Set target azure VM name given by the user. + * + * @param recoveryAzureVMName the recoveryAzureVMName value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withRecoveryAzureVMName(String recoveryAzureVMName) { + this.recoveryAzureVMName = recoveryAzureVMName; + return this; + } + + /** + * Get target Azure Vm size. + * + * @return the recoveryAzureVMSize value + */ + public String recoveryAzureVMSize() { + return this.recoveryAzureVMSize; + } + + /** + * Set target Azure Vm size. + * + * @param recoveryAzureVMSize the recoveryAzureVMSize value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withRecoveryAzureVMSize(String recoveryAzureVMSize) { + this.recoveryAzureVMSize = recoveryAzureVMSize; + return this; + } + + /** + * Get target Azure Network Id. + * + * @return the selectedRecoveryAzureNetworkId value + */ + public String selectedRecoveryAzureNetworkId() { + return this.selectedRecoveryAzureNetworkId; + } + + /** + * Set target Azure Network Id. + * + * @param selectedRecoveryAzureNetworkId the selectedRecoveryAzureNetworkId value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withSelectedRecoveryAzureNetworkId(String selectedRecoveryAzureNetworkId) { + this.selectedRecoveryAzureNetworkId = selectedRecoveryAzureNetworkId; + return this; + } + + /** + * Get the selected source nic Id which will be used as the primary nic during failover. + * + * @return the selectedSourceNicId value + */ + public String selectedSourceNicId() { + return this.selectedSourceNicId; + } + + /** + * Set the selected source nic Id which will be used as the primary nic during failover. + * + * @param selectedSourceNicId the selectedSourceNicId value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withSelectedSourceNicId(String selectedSourceNicId) { + this.selectedSourceNicId = selectedSourceNicId; + return this; + } + + /** + * Get the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @return the enableRdpOnTargetOption value + */ + public String enableRdpOnTargetOption() { + return this.enableRdpOnTargetOption; + } + + /** + * Set the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum. + * + * @param enableRdpOnTargetOption the enableRdpOnTargetOption value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withEnableRdpOnTargetOption(String enableRdpOnTargetOption) { + this.enableRdpOnTargetOption = enableRdpOnTargetOption; + return this; + } + + /** + * Get the list of vm nic details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the list of vm nic details. + * + * @param vmNics the vmNics value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get license type. Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer'. + * + * @return the licenseType value + */ + public LicenseType licenseType() { + return this.licenseType; + } + + /** + * Set license type. Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer'. + * + * @param licenseType the licenseType value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withLicenseType(LicenseType licenseType) { + this.licenseType = licenseType; + return this; + } + + /** + * Get the target availability set id. + * + * @return the recoveryAvailabilitySetId value + */ + public String recoveryAvailabilitySetId() { + return this.recoveryAvailabilitySetId; + } + + /** + * Set the target availability set id. + * + * @param recoveryAvailabilitySetId the recoveryAvailabilitySetId value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withRecoveryAvailabilitySetId(String recoveryAvailabilitySetId) { + this.recoveryAvailabilitySetId = recoveryAvailabilitySetId; + return this; + } + + /** + * Get the provider specific input to update replication protected item. + * + * @return the providerSpecificDetails value + */ + public UpdateReplicationProtectedItemProviderInput providerSpecificDetails() { + return this.providerSpecificDetails; + } + + /** + * Set the provider specific input to update replication protected item. + * + * @param providerSpecificDetails the providerSpecificDetails value to set + * @return the UpdateReplicationProtectedItemInputProperties object itself. + */ + public UpdateReplicationProtectedItemInputProperties withProviderSpecificDetails(UpdateReplicationProtectedItemProviderInput providerSpecificDetails) { + this.providerSpecificDetails = providerSpecificDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemProviderInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemProviderInput.java new file mode 100644 index 0000000000000..57fa2d093ec95 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateReplicationProtectedItemProviderInput.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonSubTypes; + +/** + * Update replication protected item provider specific input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("UpdateReplicationProtectedItemProviderInput") +@JsonSubTypes({ + @JsonSubTypes.Type(name = "A2A", value = A2AUpdateReplicationProtectedItemInput.class), + @JsonSubTypes.Type(name = "HyperVReplicaAzure", value = HyperVReplicaAzureUpdateReplicationProtectedItemInput.class), + @JsonSubTypes.Type(name = "InMageAzureV2", value = InMageAzureV2UpdateReplicationProtectedItemInput.class) +}) +public class UpdateReplicationProtectedItemProviderInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateVCenterRequest.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateVCenterRequest.java new file mode 100644 index 0000000000000..a37b8aaba7bd2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateVCenterRequest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Input required to update vCenter. + */ +public class UpdateVCenterRequest { + /** + * The update VCenter Request Properties. + */ + @JsonProperty(value = "properties") + private UpdateVCenterRequestProperties properties; + + /** + * Get the update VCenter Request Properties. + * + * @return the properties value + */ + public UpdateVCenterRequestProperties properties() { + return this.properties; + } + + /** + * Set the update VCenter Request Properties. + * + * @param properties the properties value to set + * @return the UpdateVCenterRequest object itself. + */ + public UpdateVCenterRequest withProperties(UpdateVCenterRequestProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateVCenterRequestProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateVCenterRequestProperties.java new file mode 100644 index 0000000000000..85863380c06f7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/UpdateVCenterRequestProperties.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The properties of an update vCenter request. + */ +public class UpdateVCenterRequestProperties { + /** + * The friendly name of the vCenter. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * The IP address of the vCenter to be discovered. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The process server Id from where the update can be orchestrated. + */ + @JsonProperty(value = "processServerId") + private String processServerId; + + /** + * The port number for discovery. + */ + @JsonProperty(value = "port") + private String port; + + /** + * The CS account Id which has privileges to update the vCenter. + */ + @JsonProperty(value = "runAsAccountId") + private String runAsAccountId; + + /** + * Get the friendly name of the vCenter. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set the friendly name of the vCenter. + * + * @param friendlyName the friendlyName value to set + * @return the UpdateVCenterRequestProperties object itself. + */ + public UpdateVCenterRequestProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get the IP address of the vCenter to be discovered. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the IP address of the vCenter to be discovered. + * + * @param ipAddress the ipAddress value to set + * @return the UpdateVCenterRequestProperties object itself. + */ + public UpdateVCenterRequestProperties withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the process server Id from where the update can be orchestrated. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the process server Id from where the update can be orchestrated. + * + * @param processServerId the processServerId value to set + * @return the UpdateVCenterRequestProperties object itself. + */ + public UpdateVCenterRequestProperties withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the port number for discovery. + * + * @return the port value + */ + public String port() { + return this.port; + } + + /** + * Set the port number for discovery. + * + * @param port the port value to set + * @return the UpdateVCenterRequestProperties object itself. + */ + public UpdateVCenterRequestProperties withPort(String port) { + this.port = port; + return this; + } + + /** + * Get the CS account Id which has privileges to update the vCenter. + * + * @return the runAsAccountId value + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Set the CS account Id which has privileges to update the vCenter. + * + * @param runAsAccountId the runAsAccountId value to set + * @return the UpdateVCenterRequestProperties object itself. + */ + public UpdateVCenterRequestProperties withRunAsAccountId(String runAsAccountId) { + this.runAsAccountId = runAsAccountId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VCenter.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VCenter.java new file mode 100644 index 0000000000000..2adeec15dd74d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VCenter.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.VCenterInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; + +/** + * Type representing VCenter. + */ +public interface VCenter extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + VCenterProperties properties(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the VCenter definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithReplicationFabric, DefinitionStages.WithProperties, DefinitionStages.WithCreate { + } + + /** + * Grouping of VCenter definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a VCenter definition. + */ + interface Blank extends WithReplicationFabric { + } + + /** + * The stage of the vcenter definition allowing to specify ReplicationFabric. + */ + interface WithReplicationFabric { + /** + * Specifies fabricName. + * @param fabricName Fabric name + * @return the next definition stage + */ + WithProperties withExistingReplicationFabric(String fabricName); + } + + /** + * The stage of the vcenter definition allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties The properties of an add vCenter request + * @return the next definition stage + */ + WithCreate withProperties(AddVCenterRequestProperties properties); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable { + } + } + /** + * The template for a VCenter update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithProperties { + } + + /** + * Grouping of VCenter update stages. + */ + interface UpdateStages { + /** + * The stage of the vcenter update allowing to specify Properties. + */ + interface WithProperties { + /** + * Specifies properties. + * @param properties The update VCenter Request Properties + * @return the next update stage + */ + Update withProperties(UpdateVCenterRequestProperties properties); + } + + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VCenterProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VCenterProperties.java new file mode 100644 index 0000000000000..2364244f5781b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VCenterProperties.java @@ -0,0 +1,305 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * vCenter properties. + */ +public class VCenterProperties { + /** + * Friendly name of the vCenter. + */ + @JsonProperty(value = "friendlyName") + private String friendlyName; + + /** + * VCenter internal ID. + */ + @JsonProperty(value = "internalId") + private String internalId; + + /** + * The time when the last heartbeat was received by vCenter. + */ + @JsonProperty(value = "lastHeartbeat") + private DateTime lastHeartbeat; + + /** + * The VCenter discovery status. + */ + @JsonProperty(value = "discoveryStatus") + private String discoveryStatus; + + /** + * The process server Id. + */ + @JsonProperty(value = "processServerId") + private String processServerId; + + /** + * The IP address of the vCenter. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The infrastructure Id of vCenter. + */ + @JsonProperty(value = "infrastructureId") + private String infrastructureId; + + /** + * The port number for discovery. + */ + @JsonProperty(value = "port") + private String port; + + /** + * The account Id which has privileges to discover the vCenter. + */ + @JsonProperty(value = "runAsAccountId") + private String runAsAccountId; + + /** + * The ARM resource name of the fabric containing this VCenter. + */ + @JsonProperty(value = "fabricArmResourceName") + private String fabricArmResourceName; + + /** + * The health errors for this VCenter. + */ + @JsonProperty(value = "healthErrors") + private List healthErrors; + + /** + * Get friendly name of the vCenter. + * + * @return the friendlyName value + */ + public String friendlyName() { + return this.friendlyName; + } + + /** + * Set friendly name of the vCenter. + * + * @param friendlyName the friendlyName value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + return this; + } + + /** + * Get vCenter internal ID. + * + * @return the internalId value + */ + public String internalId() { + return this.internalId; + } + + /** + * Set vCenter internal ID. + * + * @param internalId the internalId value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withInternalId(String internalId) { + this.internalId = internalId; + return this; + } + + /** + * Get the time when the last heartbeat was received by vCenter. + * + * @return the lastHeartbeat value + */ + public DateTime lastHeartbeat() { + return this.lastHeartbeat; + } + + /** + * Set the time when the last heartbeat was received by vCenter. + * + * @param lastHeartbeat the lastHeartbeat value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withLastHeartbeat(DateTime lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + return this; + } + + /** + * Get the VCenter discovery status. + * + * @return the discoveryStatus value + */ + public String discoveryStatus() { + return this.discoveryStatus; + } + + /** + * Set the VCenter discovery status. + * + * @param discoveryStatus the discoveryStatus value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withDiscoveryStatus(String discoveryStatus) { + this.discoveryStatus = discoveryStatus; + return this; + } + + /** + * Get the process server Id. + * + * @return the processServerId value + */ + public String processServerId() { + return this.processServerId; + } + + /** + * Set the process server Id. + * + * @param processServerId the processServerId value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withProcessServerId(String processServerId) { + this.processServerId = processServerId; + return this; + } + + /** + * Get the IP address of the vCenter. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the IP address of the vCenter. + * + * @param ipAddress the ipAddress value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the infrastructure Id of vCenter. + * + * @return the infrastructureId value + */ + public String infrastructureId() { + return this.infrastructureId; + } + + /** + * Set the infrastructure Id of vCenter. + * + * @param infrastructureId the infrastructureId value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withInfrastructureId(String infrastructureId) { + this.infrastructureId = infrastructureId; + return this; + } + + /** + * Get the port number for discovery. + * + * @return the port value + */ + public String port() { + return this.port; + } + + /** + * Set the port number for discovery. + * + * @param port the port value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withPort(String port) { + this.port = port; + return this; + } + + /** + * Get the account Id which has privileges to discover the vCenter. + * + * @return the runAsAccountId value + */ + public String runAsAccountId() { + return this.runAsAccountId; + } + + /** + * Set the account Id which has privileges to discover the vCenter. + * + * @param runAsAccountId the runAsAccountId value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withRunAsAccountId(String runAsAccountId) { + this.runAsAccountId = runAsAccountId; + return this; + } + + /** + * Get the ARM resource name of the fabric containing this VCenter. + * + * @return the fabricArmResourceName value + */ + public String fabricArmResourceName() { + return this.fabricArmResourceName; + } + + /** + * Set the ARM resource name of the fabric containing this VCenter. + * + * @param fabricArmResourceName the fabricArmResourceName value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withFabricArmResourceName(String fabricArmResourceName) { + this.fabricArmResourceName = fabricArmResourceName; + return this; + } + + /** + * Get the health errors for this VCenter. + * + * @return the healthErrors value + */ + public List healthErrors() { + return this.healthErrors; + } + + /** + * Set the health errors for this VCenter. + * + * @param healthErrors the healthErrors value to set + * @return the VCenterProperties object itself. + */ + public VCenterProperties withHealthErrors(List healthErrors) { + this.healthErrors = healthErrors; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMNicDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMNicDetails.java new file mode 100644 index 0000000000000..8e6fbb4fc600b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMNicDetails.java @@ -0,0 +1,355 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Hyper V VM network details. + */ +public class VMNicDetails { + /** + * The nic Id. + */ + @JsonProperty(value = "nicId") + private String nicId; + + /** + * The replica nic Id. + */ + @JsonProperty(value = "replicaNicId") + private String replicaNicId; + + /** + * The source nic ARM Id. + */ + @JsonProperty(value = "sourceNicArmId") + private String sourceNicArmId; + + /** + * VM subnet name. + */ + @JsonProperty(value = "vMSubnetName") + private String vMSubnetName; + + /** + * VM network name. + */ + @JsonProperty(value = "vMNetworkName") + private String vMNetworkName; + + /** + * Recovery VM network Id. + */ + @JsonProperty(value = "recoveryVMNetworkId") + private String recoveryVMNetworkId; + + /** + * Recovery VM subnet name. + */ + @JsonProperty(value = "recoveryVMSubnetName") + private String recoveryVMSubnetName; + + /** + * Ip address type. + */ + @JsonProperty(value = "ipAddressType") + private String ipAddressType; + + /** + * Primary nic static IP address. + */ + @JsonProperty(value = "primaryNicStaticIPAddress") + private String primaryNicStaticIPAddress; + + /** + * Replica nic static IP address. + */ + @JsonProperty(value = "replicaNicStaticIPAddress") + private String replicaNicStaticIPAddress; + + /** + * Selection type for failover. + */ + @JsonProperty(value = "selectionType") + private String selectionType; + + /** + * IP allocation type for recovery VM. + */ + @JsonProperty(value = "recoveryNicIpAddressType") + private String recoveryNicIpAddressType; + + /** + * A value indicating whether the NIC has accelerated networking enabled. + */ + @JsonProperty(value = "enableAcceleratedNetworkingOnRecovery") + private Boolean enableAcceleratedNetworkingOnRecovery; + + /** + * Get the nic Id. + * + * @return the nicId value + */ + public String nicId() { + return this.nicId; + } + + /** + * Set the nic Id. + * + * @param nicId the nicId value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withNicId(String nicId) { + this.nicId = nicId; + return this; + } + + /** + * Get the replica nic Id. + * + * @return the replicaNicId value + */ + public String replicaNicId() { + return this.replicaNicId; + } + + /** + * Set the replica nic Id. + * + * @param replicaNicId the replicaNicId value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withReplicaNicId(String replicaNicId) { + this.replicaNicId = replicaNicId; + return this; + } + + /** + * Get the source nic ARM Id. + * + * @return the sourceNicArmId value + */ + public String sourceNicArmId() { + return this.sourceNicArmId; + } + + /** + * Set the source nic ARM Id. + * + * @param sourceNicArmId the sourceNicArmId value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withSourceNicArmId(String sourceNicArmId) { + this.sourceNicArmId = sourceNicArmId; + return this; + } + + /** + * Get vM subnet name. + * + * @return the vMSubnetName value + */ + public String vMSubnetName() { + return this.vMSubnetName; + } + + /** + * Set vM subnet name. + * + * @param vMSubnetName the vMSubnetName value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withVMSubnetName(String vMSubnetName) { + this.vMSubnetName = vMSubnetName; + return this; + } + + /** + * Get vM network name. + * + * @return the vMNetworkName value + */ + public String vMNetworkName() { + return this.vMNetworkName; + } + + /** + * Set vM network name. + * + * @param vMNetworkName the vMNetworkName value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withVMNetworkName(String vMNetworkName) { + this.vMNetworkName = vMNetworkName; + return this; + } + + /** + * Get recovery VM network Id. + * + * @return the recoveryVMNetworkId value + */ + public String recoveryVMNetworkId() { + return this.recoveryVMNetworkId; + } + + /** + * Set recovery VM network Id. + * + * @param recoveryVMNetworkId the recoveryVMNetworkId value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withRecoveryVMNetworkId(String recoveryVMNetworkId) { + this.recoveryVMNetworkId = recoveryVMNetworkId; + return this; + } + + /** + * Get recovery VM subnet name. + * + * @return the recoveryVMSubnetName value + */ + public String recoveryVMSubnetName() { + return this.recoveryVMSubnetName; + } + + /** + * Set recovery VM subnet name. + * + * @param recoveryVMSubnetName the recoveryVMSubnetName value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withRecoveryVMSubnetName(String recoveryVMSubnetName) { + this.recoveryVMSubnetName = recoveryVMSubnetName; + return this; + } + + /** + * Get ip address type. + * + * @return the ipAddressType value + */ + public String ipAddressType() { + return this.ipAddressType; + } + + /** + * Set ip address type. + * + * @param ipAddressType the ipAddressType value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withIpAddressType(String ipAddressType) { + this.ipAddressType = ipAddressType; + return this; + } + + /** + * Get primary nic static IP address. + * + * @return the primaryNicStaticIPAddress value + */ + public String primaryNicStaticIPAddress() { + return this.primaryNicStaticIPAddress; + } + + /** + * Set primary nic static IP address. + * + * @param primaryNicStaticIPAddress the primaryNicStaticIPAddress value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withPrimaryNicStaticIPAddress(String primaryNicStaticIPAddress) { + this.primaryNicStaticIPAddress = primaryNicStaticIPAddress; + return this; + } + + /** + * Get replica nic static IP address. + * + * @return the replicaNicStaticIPAddress value + */ + public String replicaNicStaticIPAddress() { + return this.replicaNicStaticIPAddress; + } + + /** + * Set replica nic static IP address. + * + * @param replicaNicStaticIPAddress the replicaNicStaticIPAddress value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withReplicaNicStaticIPAddress(String replicaNicStaticIPAddress) { + this.replicaNicStaticIPAddress = replicaNicStaticIPAddress; + return this; + } + + /** + * Get selection type for failover. + * + * @return the selectionType value + */ + public String selectionType() { + return this.selectionType; + } + + /** + * Set selection type for failover. + * + * @param selectionType the selectionType value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withSelectionType(String selectionType) { + this.selectionType = selectionType; + return this; + } + + /** + * Get iP allocation type for recovery VM. + * + * @return the recoveryNicIpAddressType value + */ + public String recoveryNicIpAddressType() { + return this.recoveryNicIpAddressType; + } + + /** + * Set iP allocation type for recovery VM. + * + * @param recoveryNicIpAddressType the recoveryNicIpAddressType value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withRecoveryNicIpAddressType(String recoveryNicIpAddressType) { + this.recoveryNicIpAddressType = recoveryNicIpAddressType; + return this; + } + + /** + * Get a value indicating whether the NIC has accelerated networking enabled. + * + * @return the enableAcceleratedNetworkingOnRecovery value + */ + public Boolean enableAcceleratedNetworkingOnRecovery() { + return this.enableAcceleratedNetworkingOnRecovery; + } + + /** + * Set a value indicating whether the NIC has accelerated networking enabled. + * + * @param enableAcceleratedNetworkingOnRecovery the enableAcceleratedNetworkingOnRecovery value to set + * @return the VMNicDetails object itself. + */ + public VMNicDetails withEnableAcceleratedNetworkingOnRecovery(Boolean enableAcceleratedNetworkingOnRecovery) { + this.enableAcceleratedNetworkingOnRecovery = enableAcceleratedNetworkingOnRecovery; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMNicInputDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMNicInputDetails.java new file mode 100644 index 0000000000000..73c9013db1108 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMNicInputDetails.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Hyper V VM network input details. + */ +public class VMNicInputDetails { + /** + * The nic Id. + */ + @JsonProperty(value = "nicId") + private String nicId; + + /** + * Recovery VM subnet name. + */ + @JsonProperty(value = "recoveryVMSubnetName") + private String recoveryVMSubnetName; + + /** + * Replica nic static IP address. + */ + @JsonProperty(value = "replicaNicStaticIPAddress") + private String replicaNicStaticIPAddress; + + /** + * Selection type for failover. + */ + @JsonProperty(value = "selectionType") + private String selectionType; + + /** + * Whether the NIC has accelerated networking enabled. + */ + @JsonProperty(value = "enableAcceleratedNetworkingOnRecovery") + private Boolean enableAcceleratedNetworkingOnRecovery; + + /** + * Get the nic Id. + * + * @return the nicId value + */ + public String nicId() { + return this.nicId; + } + + /** + * Set the nic Id. + * + * @param nicId the nicId value to set + * @return the VMNicInputDetails object itself. + */ + public VMNicInputDetails withNicId(String nicId) { + this.nicId = nicId; + return this; + } + + /** + * Get recovery VM subnet name. + * + * @return the recoveryVMSubnetName value + */ + public String recoveryVMSubnetName() { + return this.recoveryVMSubnetName; + } + + /** + * Set recovery VM subnet name. + * + * @param recoveryVMSubnetName the recoveryVMSubnetName value to set + * @return the VMNicInputDetails object itself. + */ + public VMNicInputDetails withRecoveryVMSubnetName(String recoveryVMSubnetName) { + this.recoveryVMSubnetName = recoveryVMSubnetName; + return this; + } + + /** + * Get replica nic static IP address. + * + * @return the replicaNicStaticIPAddress value + */ + public String replicaNicStaticIPAddress() { + return this.replicaNicStaticIPAddress; + } + + /** + * Set replica nic static IP address. + * + * @param replicaNicStaticIPAddress the replicaNicStaticIPAddress value to set + * @return the VMNicInputDetails object itself. + */ + public VMNicInputDetails withReplicaNicStaticIPAddress(String replicaNicStaticIPAddress) { + this.replicaNicStaticIPAddress = replicaNicStaticIPAddress; + return this; + } + + /** + * Get selection type for failover. + * + * @return the selectionType value + */ + public String selectionType() { + return this.selectionType; + } + + /** + * Set selection type for failover. + * + * @param selectionType the selectionType value to set + * @return the VMNicInputDetails object itself. + */ + public VMNicInputDetails withSelectionType(String selectionType) { + this.selectionType = selectionType; + return this; + } + + /** + * Get whether the NIC has accelerated networking enabled. + * + * @return the enableAcceleratedNetworkingOnRecovery value + */ + public Boolean enableAcceleratedNetworkingOnRecovery() { + return this.enableAcceleratedNetworkingOnRecovery; + } + + /** + * Set whether the NIC has accelerated networking enabled. + * + * @param enableAcceleratedNetworkingOnRecovery the enableAcceleratedNetworkingOnRecovery value to set + * @return the VMNicInputDetails object itself. + */ + public VMNicInputDetails withEnableAcceleratedNetworkingOnRecovery(Boolean enableAcceleratedNetworkingOnRecovery) { + this.enableAcceleratedNetworkingOnRecovery = enableAcceleratedNetworkingOnRecovery; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtContainerCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtContainerCreationInput.java new file mode 100644 index 0000000000000..f6268b80bdb5f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtContainerCreationInput.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareCbt container creation input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("6c7da455-506f-43ff-a16a-8eb101aebb70") +public class VMwareCbtContainerCreationInput extends ReplicationProviderSpecificContainerCreationInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtContainerMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtContainerMappingInput.java new file mode 100644 index 0000000000000..3ad43edf5e570 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtContainerMappingInput.java @@ -0,0 +1,177 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareCbt container mapping input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VMwareCbtContainerMappingInput extends ReplicationProviderSpecificContainerMappingInput { + /** + * The target key vault ARM Id. + */ + @JsonProperty(value = "keyVaultId", required = true) + private String keyVaultId; + + /** + * The target key vault URL. + */ + @JsonProperty(value = "keyVaultUri", required = true) + private String keyVaultUri; + + /** + * The storage account ARM Id. + */ + @JsonProperty(value = "storageAccountId", required = true) + private String storageAccountId; + + /** + * The secret name of the storage account. + */ + @JsonProperty(value = "storageAccountSasSecretName", required = true) + private String storageAccountSasSecretName; + + /** + * The secret name of the service bus connection string. + */ + @JsonProperty(value = "serviceBusConnectionStringSecretName", required = true) + private String serviceBusConnectionStringSecretName; + + /** + * The target location. + */ + @JsonProperty(value = "targetLocation", required = true) + private String targetLocation; + + /** + * Get the target key vault ARM Id. + * + * @return the keyVaultId value + */ + public String keyVaultId() { + return this.keyVaultId; + } + + /** + * Set the target key vault ARM Id. + * + * @param keyVaultId the keyVaultId value to set + * @return the VMwareCbtContainerMappingInput object itself. + */ + public VMwareCbtContainerMappingInput withKeyVaultId(String keyVaultId) { + this.keyVaultId = keyVaultId; + return this; + } + + /** + * Get the target key vault URL. + * + * @return the keyVaultUri value + */ + public String keyVaultUri() { + return this.keyVaultUri; + } + + /** + * Set the target key vault URL. + * + * @param keyVaultUri the keyVaultUri value to set + * @return the VMwareCbtContainerMappingInput object itself. + */ + public VMwareCbtContainerMappingInput withKeyVaultUri(String keyVaultUri) { + this.keyVaultUri = keyVaultUri; + return this; + } + + /** + * Get the storage account ARM Id. + * + * @return the storageAccountId value + */ + public String storageAccountId() { + return this.storageAccountId; + } + + /** + * Set the storage account ARM Id. + * + * @param storageAccountId the storageAccountId value to set + * @return the VMwareCbtContainerMappingInput object itself. + */ + public VMwareCbtContainerMappingInput withStorageAccountId(String storageAccountId) { + this.storageAccountId = storageAccountId; + return this; + } + + /** + * Get the secret name of the storage account. + * + * @return the storageAccountSasSecretName value + */ + public String storageAccountSasSecretName() { + return this.storageAccountSasSecretName; + } + + /** + * Set the secret name of the storage account. + * + * @param storageAccountSasSecretName the storageAccountSasSecretName value to set + * @return the VMwareCbtContainerMappingInput object itself. + */ + public VMwareCbtContainerMappingInput withStorageAccountSasSecretName(String storageAccountSasSecretName) { + this.storageAccountSasSecretName = storageAccountSasSecretName; + return this; + } + + /** + * Get the secret name of the service bus connection string. + * + * @return the serviceBusConnectionStringSecretName value + */ + public String serviceBusConnectionStringSecretName() { + return this.serviceBusConnectionStringSecretName; + } + + /** + * Set the secret name of the service bus connection string. + * + * @param serviceBusConnectionStringSecretName the serviceBusConnectionStringSecretName value to set + * @return the VMwareCbtContainerMappingInput object itself. + */ + public VMwareCbtContainerMappingInput withServiceBusConnectionStringSecretName(String serviceBusConnectionStringSecretName) { + this.serviceBusConnectionStringSecretName = serviceBusConnectionStringSecretName; + return this; + } + + /** + * Get the target location. + * + * @return the targetLocation value + */ + public String targetLocation() { + return this.targetLocation; + } + + /** + * Set the target location. + * + * @param targetLocation the targetLocation value to set + * @return the VMwareCbtContainerMappingInput object itself. + */ + public VMwareCbtContainerMappingInput withTargetLocation(String targetLocation) { + this.targetLocation = targetLocation; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtDiskInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtDiskInput.java new file mode 100644 index 0000000000000..12a0781a08fe8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtDiskInput.java @@ -0,0 +1,148 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * VMwareCbt disk input. + */ +public class VMwareCbtDiskInput { + /** + * The disk Id. + */ + @JsonProperty(value = "diskId", required = true) + private String diskId; + + /** + * A value indicating whether the disk is the OS disk. + */ + @JsonProperty(value = "isOSDisk", required = true) + private String isOSDisk; + + /** + * The log storage account ARM Id. + */ + @JsonProperty(value = "logStorageAccountId", required = true) + private String logStorageAccountId; + + /** + * The key vault secret name of the log storage account. + */ + @JsonProperty(value = "logStorageAccountSasSecretName", required = true) + private String logStorageAccountSasSecretName; + + /** + * The disk type. Possible values include: 'Standard_LRS', 'Premium_LRS', + * 'StandardSSD_LRS'. + */ + @JsonProperty(value = "diskType") + private DiskAccountType diskType; + + /** + * Get the disk Id. + * + * @return the diskId value + */ + public String diskId() { + return this.diskId; + } + + /** + * Set the disk Id. + * + * @param diskId the diskId value to set + * @return the VMwareCbtDiskInput object itself. + */ + public VMwareCbtDiskInput withDiskId(String diskId) { + this.diskId = diskId; + return this; + } + + /** + * Get a value indicating whether the disk is the OS disk. + * + * @return the isOSDisk value + */ + public String isOSDisk() { + return this.isOSDisk; + } + + /** + * Set a value indicating whether the disk is the OS disk. + * + * @param isOSDisk the isOSDisk value to set + * @return the VMwareCbtDiskInput object itself. + */ + public VMwareCbtDiskInput withIsOSDisk(String isOSDisk) { + this.isOSDisk = isOSDisk; + return this; + } + + /** + * Get the log storage account ARM Id. + * + * @return the logStorageAccountId value + */ + public String logStorageAccountId() { + return this.logStorageAccountId; + } + + /** + * Set the log storage account ARM Id. + * + * @param logStorageAccountId the logStorageAccountId value to set + * @return the VMwareCbtDiskInput object itself. + */ + public VMwareCbtDiskInput withLogStorageAccountId(String logStorageAccountId) { + this.logStorageAccountId = logStorageAccountId; + return this; + } + + /** + * Get the key vault secret name of the log storage account. + * + * @return the logStorageAccountSasSecretName value + */ + public String logStorageAccountSasSecretName() { + return this.logStorageAccountSasSecretName; + } + + /** + * Set the key vault secret name of the log storage account. + * + * @param logStorageAccountSasSecretName the logStorageAccountSasSecretName value to set + * @return the VMwareCbtDiskInput object itself. + */ + public VMwareCbtDiskInput withLogStorageAccountSasSecretName(String logStorageAccountSasSecretName) { + this.logStorageAccountSasSecretName = logStorageAccountSasSecretName; + return this; + } + + /** + * Get the disk type. Possible values include: 'Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS'. + * + * @return the diskType value + */ + public DiskAccountType diskType() { + return this.diskType; + } + + /** + * Set the disk type. Possible values include: 'Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS'. + * + * @param diskType the diskType value to set + * @return the VMwareCbtDiskInput object itself. + */ + public VMwareCbtDiskInput withDiskType(DiskAccountType diskType) { + this.diskType = diskType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtEnableMigrationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtEnableMigrationInput.java new file mode 100644 index 0000000000000..8062e685151f2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtEnableMigrationInput.java @@ -0,0 +1,335 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareCbt specific enable migration input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VMwareCbtEnableMigrationInput extends EnableMigrationProviderSpecificInput { + /** + * The ARM Id of the VM discovered in VMware. + */ + @JsonProperty(value = "vmwareMachineId", required = true) + private String vmwareMachineId; + + /** + * The disks to include list. + */ + @JsonProperty(value = "disksToInclude", required = true) + private List disksToInclude; + + /** + * License type. Possible values include: 'NotSpecified', 'NoLicenseType', + * 'WindowsServer'. + */ + @JsonProperty(value = "licenseType") + private LicenseType licenseType; + + /** + * The data mover RunAs account Id. + */ + @JsonProperty(value = "dataMoverRunAsAccountId", required = true) + private String dataMoverRunAsAccountId; + + /** + * The snapshot RunAs account Id. + */ + @JsonProperty(value = "snapshotRunAsAccountId", required = true) + private String snapshotRunAsAccountId; + + /** + * The target VM name. + */ + @JsonProperty(value = "targetVmName") + private String targetVmName; + + /** + * The target VM size. + */ + @JsonProperty(value = "targetVmSize") + private String targetVmSize; + + /** + * The target resource group ARM Id. + */ + @JsonProperty(value = "targetResourceGroupId", required = true) + private String targetResourceGroupId; + + /** + * The target network ARM Id. + */ + @JsonProperty(value = "targetNetworkId", required = true) + private String targetNetworkId; + + /** + * The target subnet name. + */ + @JsonProperty(value = "targetSubnetName") + private String targetSubnetName; + + /** + * The target availability set ARM Id. + */ + @JsonProperty(value = "targetAvailabilitySetId") + private String targetAvailabilitySetId; + + /** + * The target boot diagnostics storage account ARM Id. + */ + @JsonProperty(value = "targetBootDiagnosticsStorageAccountId") + private String targetBootDiagnosticsStorageAccountId; + + /** + * Get the ARM Id of the VM discovered in VMware. + * + * @return the vmwareMachineId value + */ + public String vmwareMachineId() { + return this.vmwareMachineId; + } + + /** + * Set the ARM Id of the VM discovered in VMware. + * + * @param vmwareMachineId the vmwareMachineId value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withVmwareMachineId(String vmwareMachineId) { + this.vmwareMachineId = vmwareMachineId; + return this; + } + + /** + * Get the disks to include list. + * + * @return the disksToInclude value + */ + public List disksToInclude() { + return this.disksToInclude; + } + + /** + * Set the disks to include list. + * + * @param disksToInclude the disksToInclude value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withDisksToInclude(List disksToInclude) { + this.disksToInclude = disksToInclude; + return this; + } + + /** + * Get license type. Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer'. + * + * @return the licenseType value + */ + public LicenseType licenseType() { + return this.licenseType; + } + + /** + * Set license type. Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer'. + * + * @param licenseType the licenseType value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withLicenseType(LicenseType licenseType) { + this.licenseType = licenseType; + return this; + } + + /** + * Get the data mover RunAs account Id. + * + * @return the dataMoverRunAsAccountId value + */ + public String dataMoverRunAsAccountId() { + return this.dataMoverRunAsAccountId; + } + + /** + * Set the data mover RunAs account Id. + * + * @param dataMoverRunAsAccountId the dataMoverRunAsAccountId value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withDataMoverRunAsAccountId(String dataMoverRunAsAccountId) { + this.dataMoverRunAsAccountId = dataMoverRunAsAccountId; + return this; + } + + /** + * Get the snapshot RunAs account Id. + * + * @return the snapshotRunAsAccountId value + */ + public String snapshotRunAsAccountId() { + return this.snapshotRunAsAccountId; + } + + /** + * Set the snapshot RunAs account Id. + * + * @param snapshotRunAsAccountId the snapshotRunAsAccountId value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withSnapshotRunAsAccountId(String snapshotRunAsAccountId) { + this.snapshotRunAsAccountId = snapshotRunAsAccountId; + return this; + } + + /** + * Get the target VM name. + * + * @return the targetVmName value + */ + public String targetVmName() { + return this.targetVmName; + } + + /** + * Set the target VM name. + * + * @param targetVmName the targetVmName value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withTargetVmName(String targetVmName) { + this.targetVmName = targetVmName; + return this; + } + + /** + * Get the target VM size. + * + * @return the targetVmSize value + */ + public String targetVmSize() { + return this.targetVmSize; + } + + /** + * Set the target VM size. + * + * @param targetVmSize the targetVmSize value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withTargetVmSize(String targetVmSize) { + this.targetVmSize = targetVmSize; + return this; + } + + /** + * Get the target resource group ARM Id. + * + * @return the targetResourceGroupId value + */ + public String targetResourceGroupId() { + return this.targetResourceGroupId; + } + + /** + * Set the target resource group ARM Id. + * + * @param targetResourceGroupId the targetResourceGroupId value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withTargetResourceGroupId(String targetResourceGroupId) { + this.targetResourceGroupId = targetResourceGroupId; + return this; + } + + /** + * Get the target network ARM Id. + * + * @return the targetNetworkId value + */ + public String targetNetworkId() { + return this.targetNetworkId; + } + + /** + * Set the target network ARM Id. + * + * @param targetNetworkId the targetNetworkId value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withTargetNetworkId(String targetNetworkId) { + this.targetNetworkId = targetNetworkId; + return this; + } + + /** + * Get the target subnet name. + * + * @return the targetSubnetName value + */ + public String targetSubnetName() { + return this.targetSubnetName; + } + + /** + * Set the target subnet name. + * + * @param targetSubnetName the targetSubnetName value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withTargetSubnetName(String targetSubnetName) { + this.targetSubnetName = targetSubnetName; + return this; + } + + /** + * Get the target availability set ARM Id. + * + * @return the targetAvailabilitySetId value + */ + public String targetAvailabilitySetId() { + return this.targetAvailabilitySetId; + } + + /** + * Set the target availability set ARM Id. + * + * @param targetAvailabilitySetId the targetAvailabilitySetId value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withTargetAvailabilitySetId(String targetAvailabilitySetId) { + this.targetAvailabilitySetId = targetAvailabilitySetId; + return this; + } + + /** + * Get the target boot diagnostics storage account ARM Id. + * + * @return the targetBootDiagnosticsStorageAccountId value + */ + public String targetBootDiagnosticsStorageAccountId() { + return this.targetBootDiagnosticsStorageAccountId; + } + + /** + * Set the target boot diagnostics storage account ARM Id. + * + * @param targetBootDiagnosticsStorageAccountId the targetBootDiagnosticsStorageAccountId value to set + * @return the VMwareCbtEnableMigrationInput object itself. + */ + public VMwareCbtEnableMigrationInput withTargetBootDiagnosticsStorageAccountId(String targetBootDiagnosticsStorageAccountId) { + this.targetBootDiagnosticsStorageAccountId = targetBootDiagnosticsStorageAccountId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtMigrateInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtMigrateInput.java new file mode 100644 index 0000000000000..22292f77f166c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtMigrateInput.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareCbt specific migrate input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VMwareCbtMigrateInput extends MigrateProviderSpecificInput { + /** + * A value indicating whether VM is to be shutdown. + */ + @JsonProperty(value = "performShutdown", required = true) + private String performShutdown; + + /** + * Get a value indicating whether VM is to be shutdown. + * + * @return the performShutdown value + */ + public String performShutdown() { + return this.performShutdown; + } + + /** + * Set a value indicating whether VM is to be shutdown. + * + * @param performShutdown the performShutdown value to set + * @return the VMwareCbtMigrateInput object itself. + */ + public VMwareCbtMigrateInput withPerformShutdown(String performShutdown) { + this.performShutdown = performShutdown; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtMigrationDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtMigrationDetails.java new file mode 100644 index 0000000000000..49716b052645a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtMigrationDetails.java @@ -0,0 +1,362 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareCbt provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VMwareCbtMigrationDetails extends MigrationProviderSpecificSettings { + /** + * The ARM Id of the VM discovered in VMware. + */ + @JsonProperty(value = "vmwareMachineId", access = JsonProperty.Access.WRITE_ONLY) + private String vmwareMachineId; + + /** + * The type of the OS on the VM. + */ + @JsonProperty(value = "osType", access = JsonProperty.Access.WRITE_ONLY) + private String osType; + + /** + * License Type of the VM to be used. + */ + @JsonProperty(value = "licenseType") + private String licenseType; + + /** + * The data mover RunAs account Id. + */ + @JsonProperty(value = "dataMoverRunAsAccountId", access = JsonProperty.Access.WRITE_ONLY) + private String dataMoverRunAsAccountId; + + /** + * The snapshot RunAs account Id. + */ + @JsonProperty(value = "snapshotRunAsAccountId", access = JsonProperty.Access.WRITE_ONLY) + private String snapshotRunAsAccountId; + + /** + * Target VM name. + */ + @JsonProperty(value = "targetVmName") + private String targetVmName; + + /** + * The target VM size. + */ + @JsonProperty(value = "targetVmSize") + private String targetVmSize; + + /** + * The target location. + */ + @JsonProperty(value = "targetLocation", access = JsonProperty.Access.WRITE_ONLY) + private String targetLocation; + + /** + * The target resource group Id. + */ + @JsonProperty(value = "targetResourceGroupId") + private String targetResourceGroupId; + + /** + * The target availability set Id. + */ + @JsonProperty(value = "targetAvailabilitySetId") + private String targetAvailabilitySetId; + + /** + * The target boot diagnostics storage account ARM Id. + */ + @JsonProperty(value = "targetBootDiagnosticsStorageAccountId") + private String targetBootDiagnosticsStorageAccountId; + + /** + * The list of protected disks. + */ + @JsonProperty(value = "protectedDisks") + private List protectedDisks; + + /** + * The target network Id. + */ + @JsonProperty(value = "targetNetworkId") + private String targetNetworkId; + + /** + * The network details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * The recovery point Id to which the VM was migrated. + */ + @JsonProperty(value = "migrationRecoveryPointId", access = JsonProperty.Access.WRITE_ONLY) + private String migrationRecoveryPointId; + + /** + * The last recovery point received time. + */ + @JsonProperty(value = "lastRecoveryPointReceived", access = JsonProperty.Access.WRITE_ONLY) + private DateTime lastRecoveryPointReceived; + + /** + * Get the ARM Id of the VM discovered in VMware. + * + * @return the vmwareMachineId value + */ + public String vmwareMachineId() { + return this.vmwareMachineId; + } + + /** + * Get the type of the OS on the VM. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Get license Type of the VM to be used. + * + * @return the licenseType value + */ + public String licenseType() { + return this.licenseType; + } + + /** + * Set license Type of the VM to be used. + * + * @param licenseType the licenseType value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withLicenseType(String licenseType) { + this.licenseType = licenseType; + return this; + } + + /** + * Get the data mover RunAs account Id. + * + * @return the dataMoverRunAsAccountId value + */ + public String dataMoverRunAsAccountId() { + return this.dataMoverRunAsAccountId; + } + + /** + * Get the snapshot RunAs account Id. + * + * @return the snapshotRunAsAccountId value + */ + public String snapshotRunAsAccountId() { + return this.snapshotRunAsAccountId; + } + + /** + * Get target VM name. + * + * @return the targetVmName value + */ + public String targetVmName() { + return this.targetVmName; + } + + /** + * Set target VM name. + * + * @param targetVmName the targetVmName value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withTargetVmName(String targetVmName) { + this.targetVmName = targetVmName; + return this; + } + + /** + * Get the target VM size. + * + * @return the targetVmSize value + */ + public String targetVmSize() { + return this.targetVmSize; + } + + /** + * Set the target VM size. + * + * @param targetVmSize the targetVmSize value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withTargetVmSize(String targetVmSize) { + this.targetVmSize = targetVmSize; + return this; + } + + /** + * Get the target location. + * + * @return the targetLocation value + */ + public String targetLocation() { + return this.targetLocation; + } + + /** + * Get the target resource group Id. + * + * @return the targetResourceGroupId value + */ + public String targetResourceGroupId() { + return this.targetResourceGroupId; + } + + /** + * Set the target resource group Id. + * + * @param targetResourceGroupId the targetResourceGroupId value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withTargetResourceGroupId(String targetResourceGroupId) { + this.targetResourceGroupId = targetResourceGroupId; + return this; + } + + /** + * Get the target availability set Id. + * + * @return the targetAvailabilitySetId value + */ + public String targetAvailabilitySetId() { + return this.targetAvailabilitySetId; + } + + /** + * Set the target availability set Id. + * + * @param targetAvailabilitySetId the targetAvailabilitySetId value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withTargetAvailabilitySetId(String targetAvailabilitySetId) { + this.targetAvailabilitySetId = targetAvailabilitySetId; + return this; + } + + /** + * Get the target boot diagnostics storage account ARM Id. + * + * @return the targetBootDiagnosticsStorageAccountId value + */ + public String targetBootDiagnosticsStorageAccountId() { + return this.targetBootDiagnosticsStorageAccountId; + } + + /** + * Set the target boot diagnostics storage account ARM Id. + * + * @param targetBootDiagnosticsStorageAccountId the targetBootDiagnosticsStorageAccountId value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withTargetBootDiagnosticsStorageAccountId(String targetBootDiagnosticsStorageAccountId) { + this.targetBootDiagnosticsStorageAccountId = targetBootDiagnosticsStorageAccountId; + return this; + } + + /** + * Get the list of protected disks. + * + * @return the protectedDisks value + */ + public List protectedDisks() { + return this.protectedDisks; + } + + /** + * Set the list of protected disks. + * + * @param protectedDisks the protectedDisks value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withProtectedDisks(List protectedDisks) { + this.protectedDisks = protectedDisks; + return this; + } + + /** + * Get the target network Id. + * + * @return the targetNetworkId value + */ + public String targetNetworkId() { + return this.targetNetworkId; + } + + /** + * Set the target network Id. + * + * @param targetNetworkId the targetNetworkId value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withTargetNetworkId(String targetNetworkId) { + this.targetNetworkId = targetNetworkId; + return this; + } + + /** + * Get the network details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the network details. + * + * @param vmNics the vmNics value to set + * @return the VMwareCbtMigrationDetails object itself. + */ + public VMwareCbtMigrationDetails withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get the recovery point Id to which the VM was migrated. + * + * @return the migrationRecoveryPointId value + */ + public String migrationRecoveryPointId() { + return this.migrationRecoveryPointId; + } + + /** + * Get the last recovery point received time. + * + * @return the lastRecoveryPointReceived value + */ + public DateTime lastRecoveryPointReceived() { + return this.lastRecoveryPointReceived; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtNicDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtNicDetails.java new file mode 100644 index 0000000000000..4e5d16b3d453b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtNicDetails.java @@ -0,0 +1,209 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * VMwareCbt NIC details. + */ +public class VMwareCbtNicDetails { + /** + * The NIC Id. + */ + @JsonProperty(value = "nicId", access = JsonProperty.Access.WRITE_ONLY) + private String nicId; + + /** + * A value indicating whether this is the primary NIC. + */ + @JsonProperty(value = "isPrimaryNic") + private String isPrimaryNic; + + /** + * The source IP address. + */ + @JsonProperty(value = "sourceIPAddress", access = JsonProperty.Access.WRITE_ONLY) + private String sourceIPAddress; + + /** + * The source IP address type. Possible values include: 'Dynamic', + * 'Static'. + */ + @JsonProperty(value = "sourceIPAddressType", access = JsonProperty.Access.WRITE_ONLY) + private EthernetAddressType sourceIPAddressType; + + /** + * Source network Id. + */ + @JsonProperty(value = "sourceNetworkId", access = JsonProperty.Access.WRITE_ONLY) + private String sourceNetworkId; + + /** + * The target IP address. + */ + @JsonProperty(value = "targetIPAddress") + private String targetIPAddress; + + /** + * The target IP address type. Possible values include: 'Dynamic', + * 'Static'. + */ + @JsonProperty(value = "targetIPAddressType") + private EthernetAddressType targetIPAddressType; + + /** + * Target subnet name. + */ + @JsonProperty(value = "targetSubnetName") + private String targetSubnetName; + + /** + * A value indicating whether this NIC is selected for migration. + */ + @JsonProperty(value = "isSelectedForMigration") + private String isSelectedForMigration; + + /** + * Get the NIC Id. + * + * @return the nicId value + */ + public String nicId() { + return this.nicId; + } + + /** + * Get a value indicating whether this is the primary NIC. + * + * @return the isPrimaryNic value + */ + public String isPrimaryNic() { + return this.isPrimaryNic; + } + + /** + * Set a value indicating whether this is the primary NIC. + * + * @param isPrimaryNic the isPrimaryNic value to set + * @return the VMwareCbtNicDetails object itself. + */ + public VMwareCbtNicDetails withIsPrimaryNic(String isPrimaryNic) { + this.isPrimaryNic = isPrimaryNic; + return this; + } + + /** + * Get the source IP address. + * + * @return the sourceIPAddress value + */ + public String sourceIPAddress() { + return this.sourceIPAddress; + } + + /** + * Get the source IP address type. Possible values include: 'Dynamic', 'Static'. + * + * @return the sourceIPAddressType value + */ + public EthernetAddressType sourceIPAddressType() { + return this.sourceIPAddressType; + } + + /** + * Get source network Id. + * + * @return the sourceNetworkId value + */ + public String sourceNetworkId() { + return this.sourceNetworkId; + } + + /** + * Get the target IP address. + * + * @return the targetIPAddress value + */ + public String targetIPAddress() { + return this.targetIPAddress; + } + + /** + * Set the target IP address. + * + * @param targetIPAddress the targetIPAddress value to set + * @return the VMwareCbtNicDetails object itself. + */ + public VMwareCbtNicDetails withTargetIPAddress(String targetIPAddress) { + this.targetIPAddress = targetIPAddress; + return this; + } + + /** + * Get the target IP address type. Possible values include: 'Dynamic', 'Static'. + * + * @return the targetIPAddressType value + */ + public EthernetAddressType targetIPAddressType() { + return this.targetIPAddressType; + } + + /** + * Set the target IP address type. Possible values include: 'Dynamic', 'Static'. + * + * @param targetIPAddressType the targetIPAddressType value to set + * @return the VMwareCbtNicDetails object itself. + */ + public VMwareCbtNicDetails withTargetIPAddressType(EthernetAddressType targetIPAddressType) { + this.targetIPAddressType = targetIPAddressType; + return this; + } + + /** + * Get target subnet name. + * + * @return the targetSubnetName value + */ + public String targetSubnetName() { + return this.targetSubnetName; + } + + /** + * Set target subnet name. + * + * @param targetSubnetName the targetSubnetName value to set + * @return the VMwareCbtNicDetails object itself. + */ + public VMwareCbtNicDetails withTargetSubnetName(String targetSubnetName) { + this.targetSubnetName = targetSubnetName; + return this; + } + + /** + * Get a value indicating whether this NIC is selected for migration. + * + * @return the isSelectedForMigration value + */ + public String isSelectedForMigration() { + return this.isSelectedForMigration; + } + + /** + * Set a value indicating whether this NIC is selected for migration. + * + * @param isSelectedForMigration the isSelectedForMigration value to set + * @return the VMwareCbtNicDetails object itself. + */ + public VMwareCbtNicDetails withIsSelectedForMigration(String isSelectedForMigration) { + this.isSelectedForMigration = isSelectedForMigration; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtNicInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtNicInput.java new file mode 100644 index 0000000000000..a5e308e81e96b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtNicInput.java @@ -0,0 +1,147 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * VMwareCbt NIC input. + */ +public class VMwareCbtNicInput { + /** + * The NIC Id. + */ + @JsonProperty(value = "nicId", required = true) + private String nicId; + + /** + * A value indicating whether this is the primary NIC. + */ + @JsonProperty(value = "isPrimaryNic", required = true) + private String isPrimaryNic; + + /** + * Target subnet name. + */ + @JsonProperty(value = "targetSubnetName") + private String targetSubnetName; + + /** + * The static IP address. + */ + @JsonProperty(value = "targetStaticIPAddress") + private String targetStaticIPAddress; + + /** + * A value indicating whether this NIC is selected for migration. + */ + @JsonProperty(value = "isSelectedForMigration") + private String isSelectedForMigration; + + /** + * Get the NIC Id. + * + * @return the nicId value + */ + public String nicId() { + return this.nicId; + } + + /** + * Set the NIC Id. + * + * @param nicId the nicId value to set + * @return the VMwareCbtNicInput object itself. + */ + public VMwareCbtNicInput withNicId(String nicId) { + this.nicId = nicId; + return this; + } + + /** + * Get a value indicating whether this is the primary NIC. + * + * @return the isPrimaryNic value + */ + public String isPrimaryNic() { + return this.isPrimaryNic; + } + + /** + * Set a value indicating whether this is the primary NIC. + * + * @param isPrimaryNic the isPrimaryNic value to set + * @return the VMwareCbtNicInput object itself. + */ + public VMwareCbtNicInput withIsPrimaryNic(String isPrimaryNic) { + this.isPrimaryNic = isPrimaryNic; + return this; + } + + /** + * Get target subnet name. + * + * @return the targetSubnetName value + */ + public String targetSubnetName() { + return this.targetSubnetName; + } + + /** + * Set target subnet name. + * + * @param targetSubnetName the targetSubnetName value to set + * @return the VMwareCbtNicInput object itself. + */ + public VMwareCbtNicInput withTargetSubnetName(String targetSubnetName) { + this.targetSubnetName = targetSubnetName; + return this; + } + + /** + * Get the static IP address. + * + * @return the targetStaticIPAddress value + */ + public String targetStaticIPAddress() { + return this.targetStaticIPAddress; + } + + /** + * Set the static IP address. + * + * @param targetStaticIPAddress the targetStaticIPAddress value to set + * @return the VMwareCbtNicInput object itself. + */ + public VMwareCbtNicInput withTargetStaticIPAddress(String targetStaticIPAddress) { + this.targetStaticIPAddress = targetStaticIPAddress; + return this; + } + + /** + * Get a value indicating whether this NIC is selected for migration. + * + * @return the isSelectedForMigration value + */ + public String isSelectedForMigration() { + return this.isSelectedForMigration; + } + + /** + * Set a value indicating whether this NIC is selected for migration. + * + * @param isSelectedForMigration the isSelectedForMigration value to set + * @return the VMwareCbtNicInput object itself. + */ + public VMwareCbtNicInput withIsSelectedForMigration(String isSelectedForMigration) { + this.isSelectedForMigration = isSelectedForMigration; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtPolicyCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtPolicyCreationInput.java new file mode 100644 index 0000000000000..1f43858e42a95 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtPolicyCreationInput.java @@ -0,0 +1,100 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMware Cbt policy creation input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VMwareCbtPolicyCreationInput extends PolicyProviderSpecificInput { + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistoryInMinutes") + private Integer recoveryPointHistoryInMinutes; + + /** + * The crash consistent snapshot frequency (in minutes). + */ + @JsonProperty(value = "crashConsistentFrequencyInMinutes") + private Integer crashConsistentFrequencyInMinutes; + + /** + * The app consistent snapshot frequency (in minutes). + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistoryInMinutes value + */ + public Integer recoveryPointHistoryInMinutes() { + return this.recoveryPointHistoryInMinutes; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistoryInMinutes the recoveryPointHistoryInMinutes value to set + * @return the VMwareCbtPolicyCreationInput object itself. + */ + public VMwareCbtPolicyCreationInput withRecoveryPointHistoryInMinutes(Integer recoveryPointHistoryInMinutes) { + this.recoveryPointHistoryInMinutes = recoveryPointHistoryInMinutes; + return this; + } + + /** + * Get the crash consistent snapshot frequency (in minutes). + * + * @return the crashConsistentFrequencyInMinutes value + */ + public Integer crashConsistentFrequencyInMinutes() { + return this.crashConsistentFrequencyInMinutes; + } + + /** + * Set the crash consistent snapshot frequency (in minutes). + * + * @param crashConsistentFrequencyInMinutes the crashConsistentFrequencyInMinutes value to set + * @return the VMwareCbtPolicyCreationInput object itself. + */ + public VMwareCbtPolicyCreationInput withCrashConsistentFrequencyInMinutes(Integer crashConsistentFrequencyInMinutes) { + this.crashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes; + return this; + } + + /** + * Get the app consistent snapshot frequency (in minutes). + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency (in minutes). + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the VMwareCbtPolicyCreationInput object itself. + */ + public VMwareCbtPolicyCreationInput withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtProtectedDiskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtProtectedDiskDetails.java new file mode 100644 index 0000000000000..4bff16cc327f8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtProtectedDiskDetails.java @@ -0,0 +1,179 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * VMwareCbt protected disk details. + */ +public class VMwareCbtProtectedDiskDetails { + /** + * The disk id. + */ + @JsonProperty(value = "diskId", access = JsonProperty.Access.WRITE_ONLY) + private String diskId; + + /** + * The disk name. + */ + @JsonProperty(value = "diskName", access = JsonProperty.Access.WRITE_ONLY) + private String diskName; + + /** + * The disk path. + */ + @JsonProperty(value = "diskPath", access = JsonProperty.Access.WRITE_ONLY) + private String diskPath; + + /** + * A value indicating whether the disk is the OS disk. + */ + @JsonProperty(value = "isOSDisk", access = JsonProperty.Access.WRITE_ONLY) + private String isOSDisk; + + /** + * The disk capacity in bytes. + */ + @JsonProperty(value = "capacityInBytes", access = JsonProperty.Access.WRITE_ONLY) + private Long capacityInBytes; + + /** + * The log storage account ARM Id. + */ + @JsonProperty(value = "logStorageAccountId", access = JsonProperty.Access.WRITE_ONLY) + private String logStorageAccountId; + + /** + * The key vault secret name of the log storage account. + */ + @JsonProperty(value = "logStorageAccountSasSecretName", access = JsonProperty.Access.WRITE_ONLY) + private String logStorageAccountSasSecretName; + + /** + * The ARM Id of the seed managed disk. + */ + @JsonProperty(value = "seedManagedDiskId", access = JsonProperty.Access.WRITE_ONLY) + private String seedManagedDiskId; + + /** + * The ARM Id of the target managed disk. + */ + @JsonProperty(value = "targetManagedDiskId", access = JsonProperty.Access.WRITE_ONLY) + private String targetManagedDiskId; + + /** + * The disk type. Possible values include: 'Standard_LRS', 'Premium_LRS', + * 'StandardSSD_LRS'. + */ + @JsonProperty(value = "diskType") + private DiskType diskType; + + /** + * Get the disk id. + * + * @return the diskId value + */ + public String diskId() { + return this.diskId; + } + + /** + * Get the disk name. + * + * @return the diskName value + */ + public String diskName() { + return this.diskName; + } + + /** + * Get the disk path. + * + * @return the diskPath value + */ + public String diskPath() { + return this.diskPath; + } + + /** + * Get a value indicating whether the disk is the OS disk. + * + * @return the isOSDisk value + */ + public String isOSDisk() { + return this.isOSDisk; + } + + /** + * Get the disk capacity in bytes. + * + * @return the capacityInBytes value + */ + public Long capacityInBytes() { + return this.capacityInBytes; + } + + /** + * Get the log storage account ARM Id. + * + * @return the logStorageAccountId value + */ + public String logStorageAccountId() { + return this.logStorageAccountId; + } + + /** + * Get the key vault secret name of the log storage account. + * + * @return the logStorageAccountSasSecretName value + */ + public String logStorageAccountSasSecretName() { + return this.logStorageAccountSasSecretName; + } + + /** + * Get the ARM Id of the seed managed disk. + * + * @return the seedManagedDiskId value + */ + public String seedManagedDiskId() { + return this.seedManagedDiskId; + } + + /** + * Get the ARM Id of the target managed disk. + * + * @return the targetManagedDiskId value + */ + public String targetManagedDiskId() { + return this.targetManagedDiskId; + } + + /** + * Get the disk type. Possible values include: 'Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS'. + * + * @return the diskType value + */ + public DiskType diskType() { + return this.diskType; + } + + /** + * Set the disk type. Possible values include: 'Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS'. + * + * @param diskType the diskType value to set + * @return the VMwareCbtProtectedDiskDetails object itself. + */ + public VMwareCbtProtectedDiskDetails withDiskType(DiskType diskType) { + this.diskType = diskType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtProtectionContainerMappingDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtProtectionContainerMappingDetails.java new file mode 100644 index 0000000000000..fac5b44aec52a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtProtectionContainerMappingDetails.java @@ -0,0 +1,111 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareCbt provider specific container mapping details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VMwareCbtProtectionContainerMappingDetails extends ProtectionContainerMappingProviderSpecificDetails { + /** + * The target key vault ARM Id. + */ + @JsonProperty(value = "keyVaultId", access = JsonProperty.Access.WRITE_ONLY) + private String keyVaultId; + + /** + * The target key vault URI. + */ + @JsonProperty(value = "keyVaultUri", access = JsonProperty.Access.WRITE_ONLY) + private String keyVaultUri; + + /** + * The storage account ARM Id. + */ + @JsonProperty(value = "storageAccountId", access = JsonProperty.Access.WRITE_ONLY) + private String storageAccountId; + + /** + * The secret name of the storage account. + */ + @JsonProperty(value = "storageAccountSasSecretName", access = JsonProperty.Access.WRITE_ONLY) + private String storageAccountSasSecretName; + + /** + * The secret name of the service bus connection string. + */ + @JsonProperty(value = "serviceBusConnectionStringSecretName", access = JsonProperty.Access.WRITE_ONLY) + private String serviceBusConnectionStringSecretName; + + /** + * The target location. + */ + @JsonProperty(value = "targetLocation", access = JsonProperty.Access.WRITE_ONLY) + private String targetLocation; + + /** + * Get the target key vault ARM Id. + * + * @return the keyVaultId value + */ + public String keyVaultId() { + return this.keyVaultId; + } + + /** + * Get the target key vault URI. + * + * @return the keyVaultUri value + */ + public String keyVaultUri() { + return this.keyVaultUri; + } + + /** + * Get the storage account ARM Id. + * + * @return the storageAccountId value + */ + public String storageAccountId() { + return this.storageAccountId; + } + + /** + * Get the secret name of the storage account. + * + * @return the storageAccountSasSecretName value + */ + public String storageAccountSasSecretName() { + return this.storageAccountSasSecretName; + } + + /** + * Get the secret name of the service bus connection string. + * + * @return the serviceBusConnectionStringSecretName value + */ + public String serviceBusConnectionStringSecretName() { + return this.serviceBusConnectionStringSecretName; + } + + /** + * Get the target location. + * + * @return the targetLocation value + */ + public String targetLocation() { + return this.targetLocation; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtTestMigrateInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtTestMigrateInput.java new file mode 100644 index 0000000000000..a641490968881 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtTestMigrateInput.java @@ -0,0 +1,73 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareCbt specific test migrate input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VMwareCbtTestMigrateInput extends TestMigrateProviderSpecificInput { + /** + * The recovery point Id. + */ + @JsonProperty(value = "recoveryPointId", required = true) + private String recoveryPointId; + + /** + * The test network Id. + */ + @JsonProperty(value = "networkId", required = true) + private String networkId; + + /** + * Get the recovery point Id. + * + * @return the recoveryPointId value + */ + public String recoveryPointId() { + return this.recoveryPointId; + } + + /** + * Set the recovery point Id. + * + * @param recoveryPointId the recoveryPointId value to set + * @return the VMwareCbtTestMigrateInput object itself. + */ + public VMwareCbtTestMigrateInput withRecoveryPointId(String recoveryPointId) { + this.recoveryPointId = recoveryPointId; + return this; + } + + /** + * Get the test network Id. + * + * @return the networkId value + */ + public String networkId() { + return this.networkId; + } + + /** + * Set the test network Id. + * + * @param networkId the networkId value to set + * @return the VMwareCbtTestMigrateInput object itself. + */ + public VMwareCbtTestMigrateInput withNetworkId(String networkId) { + this.networkId = networkId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtUpdateMigrationItemInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtUpdateMigrationItemInput.java new file mode 100644 index 0000000000000..7d62abc3e8ed7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareCbtUpdateMigrationItemInput.java @@ -0,0 +1,231 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareCbt specific update migration item input. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VMwareCbtUpdateMigrationItemInput extends UpdateMigrationItemProviderSpecificInput { + /** + * The target VM name. + */ + @JsonProperty(value = "targetVmName") + private String targetVmName; + + /** + * The target VM size. + */ + @JsonProperty(value = "targetVmSize") + private String targetVmSize; + + /** + * The target resource group ARM Id. + */ + @JsonProperty(value = "targetResourceGroupId") + private String targetResourceGroupId; + + /** + * The target availability set ARM Id. + */ + @JsonProperty(value = "targetAvailabilitySetId") + private String targetAvailabilitySetId; + + /** + * The target boot diagnostics storage account ARM Id. + */ + @JsonProperty(value = "targetBootDiagnosticsStorageAccountId") + private String targetBootDiagnosticsStorageAccountId; + + /** + * The target network ARM Id. + */ + @JsonProperty(value = "targetNetworkId") + private String targetNetworkId; + + /** + * The list of NIC details. + */ + @JsonProperty(value = "vmNics") + private List vmNics; + + /** + * The license type. Possible values include: 'NotSpecified', + * 'NoLicenseType', 'WindowsServer'. + */ + @JsonProperty(value = "licenseType") + private LicenseType licenseType; + + /** + * Get the target VM name. + * + * @return the targetVmName value + */ + public String targetVmName() { + return this.targetVmName; + } + + /** + * Set the target VM name. + * + * @param targetVmName the targetVmName value to set + * @return the VMwareCbtUpdateMigrationItemInput object itself. + */ + public VMwareCbtUpdateMigrationItemInput withTargetVmName(String targetVmName) { + this.targetVmName = targetVmName; + return this; + } + + /** + * Get the target VM size. + * + * @return the targetVmSize value + */ + public String targetVmSize() { + return this.targetVmSize; + } + + /** + * Set the target VM size. + * + * @param targetVmSize the targetVmSize value to set + * @return the VMwareCbtUpdateMigrationItemInput object itself. + */ + public VMwareCbtUpdateMigrationItemInput withTargetVmSize(String targetVmSize) { + this.targetVmSize = targetVmSize; + return this; + } + + /** + * Get the target resource group ARM Id. + * + * @return the targetResourceGroupId value + */ + public String targetResourceGroupId() { + return this.targetResourceGroupId; + } + + /** + * Set the target resource group ARM Id. + * + * @param targetResourceGroupId the targetResourceGroupId value to set + * @return the VMwareCbtUpdateMigrationItemInput object itself. + */ + public VMwareCbtUpdateMigrationItemInput withTargetResourceGroupId(String targetResourceGroupId) { + this.targetResourceGroupId = targetResourceGroupId; + return this; + } + + /** + * Get the target availability set ARM Id. + * + * @return the targetAvailabilitySetId value + */ + public String targetAvailabilitySetId() { + return this.targetAvailabilitySetId; + } + + /** + * Set the target availability set ARM Id. + * + * @param targetAvailabilitySetId the targetAvailabilitySetId value to set + * @return the VMwareCbtUpdateMigrationItemInput object itself. + */ + public VMwareCbtUpdateMigrationItemInput withTargetAvailabilitySetId(String targetAvailabilitySetId) { + this.targetAvailabilitySetId = targetAvailabilitySetId; + return this; + } + + /** + * Get the target boot diagnostics storage account ARM Id. + * + * @return the targetBootDiagnosticsStorageAccountId value + */ + public String targetBootDiagnosticsStorageAccountId() { + return this.targetBootDiagnosticsStorageAccountId; + } + + /** + * Set the target boot diagnostics storage account ARM Id. + * + * @param targetBootDiagnosticsStorageAccountId the targetBootDiagnosticsStorageAccountId value to set + * @return the VMwareCbtUpdateMigrationItemInput object itself. + */ + public VMwareCbtUpdateMigrationItemInput withTargetBootDiagnosticsStorageAccountId(String targetBootDiagnosticsStorageAccountId) { + this.targetBootDiagnosticsStorageAccountId = targetBootDiagnosticsStorageAccountId; + return this; + } + + /** + * Get the target network ARM Id. + * + * @return the targetNetworkId value + */ + public String targetNetworkId() { + return this.targetNetworkId; + } + + /** + * Set the target network ARM Id. + * + * @param targetNetworkId the targetNetworkId value to set + * @return the VMwareCbtUpdateMigrationItemInput object itself. + */ + public VMwareCbtUpdateMigrationItemInput withTargetNetworkId(String targetNetworkId) { + this.targetNetworkId = targetNetworkId; + return this; + } + + /** + * Get the list of NIC details. + * + * @return the vmNics value + */ + public List vmNics() { + return this.vmNics; + } + + /** + * Set the list of NIC details. + * + * @param vmNics the vmNics value to set + * @return the VMwareCbtUpdateMigrationItemInput object itself. + */ + public VMwareCbtUpdateMigrationItemInput withVmNics(List vmNics) { + this.vmNics = vmNics; + return this; + } + + /** + * Get the license type. Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer'. + * + * @return the licenseType value + */ + public LicenseType licenseType() { + return this.licenseType; + } + + /** + * Set the license type. Possible values include: 'NotSpecified', 'NoLicenseType', 'WindowsServer'. + * + * @param licenseType the licenseType value to set + * @return the VMwareCbtUpdateMigrationItemInput object itself. + */ + public VMwareCbtUpdateMigrationItemInput withLicenseType(LicenseType licenseType) { + this.licenseType = licenseType; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareDetails.java new file mode 100644 index 0000000000000..546d8830b749b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareDetails.java @@ -0,0 +1,855 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Store the fabric details specific to the VMware fabric. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMware") +public class VMwareDetails extends FabricSpecificDetails { + /** + * The list of Process Servers associated with the fabric. + */ + @JsonProperty(value = "processServers") + private List processServers; + + /** + * The list of Master Target servers associated with the fabric. + */ + @JsonProperty(value = "masterTargetServers") + private List masterTargetServers; + + /** + * The list of run as accounts created on the server. + */ + @JsonProperty(value = "runAsAccounts") + private List runAsAccounts; + + /** + * The number of replication pairs configured in this CS. + */ + @JsonProperty(value = "replicationPairCount") + private String replicationPairCount; + + /** + * The number of process servers. + */ + @JsonProperty(value = "processServerCount") + private String processServerCount; + + /** + * The number of source and target servers configured to talk to this CS. + */ + @JsonProperty(value = "agentCount") + private String agentCount; + + /** + * The number of protected servers. + */ + @JsonProperty(value = "protectedServers") + private String protectedServers; + + /** + * The percentage of the system load. + */ + @JsonProperty(value = "systemLoad") + private String systemLoad; + + /** + * The system load status. + */ + @JsonProperty(value = "systemLoadStatus") + private String systemLoadStatus; + + /** + * The percentage of the CPU load. + */ + @JsonProperty(value = "cpuLoad") + private String cpuLoad; + + /** + * The CPU load status. + */ + @JsonProperty(value = "cpuLoadStatus") + private String cpuLoadStatus; + + /** + * The total memory. + */ + @JsonProperty(value = "totalMemoryInBytes") + private Long totalMemoryInBytes; + + /** + * The available memory. + */ + @JsonProperty(value = "availableMemoryInBytes") + private Long availableMemoryInBytes; + + /** + * The memory usage status. + */ + @JsonProperty(value = "memoryUsageStatus") + private String memoryUsageStatus; + + /** + * The total space. + */ + @JsonProperty(value = "totalSpaceInBytes") + private Long totalSpaceInBytes; + + /** + * The available space. + */ + @JsonProperty(value = "availableSpaceInBytes") + private Long availableSpaceInBytes; + + /** + * The space usage status. + */ + @JsonProperty(value = "spaceUsageStatus") + private String spaceUsageStatus; + + /** + * The web load. + */ + @JsonProperty(value = "webLoad") + private String webLoad; + + /** + * The web load status. + */ + @JsonProperty(value = "webLoadStatus") + private String webLoadStatus; + + /** + * The database server load. + */ + @JsonProperty(value = "databaseServerLoad") + private String databaseServerLoad; + + /** + * The database server load status. + */ + @JsonProperty(value = "databaseServerLoadStatus") + private String databaseServerLoadStatus; + + /** + * The CS service status. + */ + @JsonProperty(value = "csServiceStatus") + private String csServiceStatus; + + /** + * The IP address. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The agent Version. + */ + @JsonProperty(value = "agentVersion") + private String agentVersion; + + /** + * The host name. + */ + @JsonProperty(value = "hostName") + private String hostName; + + /** + * The last heartbeat received from CS server. + */ + @JsonProperty(value = "lastHeartbeat") + private DateTime lastHeartbeat; + + /** + * Version status. + */ + @JsonProperty(value = "versionStatus") + private String versionStatus; + + /** + * CS SSL cert expiry date. + */ + @JsonProperty(value = "sslCertExpiryDate") + private DateTime sslCertExpiryDate; + + /** + * CS SSL cert expiry date. + */ + @JsonProperty(value = "sslCertExpiryRemainingDays") + private Integer sslCertExpiryRemainingDays; + + /** + * PS template version. + */ + @JsonProperty(value = "psTemplateVersion") + private String psTemplateVersion; + + /** + * Agent expiry date. + */ + @JsonProperty(value = "agentExpiryDate") + private DateTime agentExpiryDate; + + /** + * The agent version details. + */ + @JsonProperty(value = "agentVersionDetails") + private VersionDetails agentVersionDetails; + + /** + * Get the list of Process Servers associated with the fabric. + * + * @return the processServers value + */ + public List processServers() { + return this.processServers; + } + + /** + * Set the list of Process Servers associated with the fabric. + * + * @param processServers the processServers value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withProcessServers(List processServers) { + this.processServers = processServers; + return this; + } + + /** + * Get the list of Master Target servers associated with the fabric. + * + * @return the masterTargetServers value + */ + public List masterTargetServers() { + return this.masterTargetServers; + } + + /** + * Set the list of Master Target servers associated with the fabric. + * + * @param masterTargetServers the masterTargetServers value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withMasterTargetServers(List masterTargetServers) { + this.masterTargetServers = masterTargetServers; + return this; + } + + /** + * Get the list of run as accounts created on the server. + * + * @return the runAsAccounts value + */ + public List runAsAccounts() { + return this.runAsAccounts; + } + + /** + * Set the list of run as accounts created on the server. + * + * @param runAsAccounts the runAsAccounts value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withRunAsAccounts(List runAsAccounts) { + this.runAsAccounts = runAsAccounts; + return this; + } + + /** + * Get the number of replication pairs configured in this CS. + * + * @return the replicationPairCount value + */ + public String replicationPairCount() { + return this.replicationPairCount; + } + + /** + * Set the number of replication pairs configured in this CS. + * + * @param replicationPairCount the replicationPairCount value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withReplicationPairCount(String replicationPairCount) { + this.replicationPairCount = replicationPairCount; + return this; + } + + /** + * Get the number of process servers. + * + * @return the processServerCount value + */ + public String processServerCount() { + return this.processServerCount; + } + + /** + * Set the number of process servers. + * + * @param processServerCount the processServerCount value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withProcessServerCount(String processServerCount) { + this.processServerCount = processServerCount; + return this; + } + + /** + * Get the number of source and target servers configured to talk to this CS. + * + * @return the agentCount value + */ + public String agentCount() { + return this.agentCount; + } + + /** + * Set the number of source and target servers configured to talk to this CS. + * + * @param agentCount the agentCount value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withAgentCount(String agentCount) { + this.agentCount = agentCount; + return this; + } + + /** + * Get the number of protected servers. + * + * @return the protectedServers value + */ + public String protectedServers() { + return this.protectedServers; + } + + /** + * Set the number of protected servers. + * + * @param protectedServers the protectedServers value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withProtectedServers(String protectedServers) { + this.protectedServers = protectedServers; + return this; + } + + /** + * Get the percentage of the system load. + * + * @return the systemLoad value + */ + public String systemLoad() { + return this.systemLoad; + } + + /** + * Set the percentage of the system load. + * + * @param systemLoad the systemLoad value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withSystemLoad(String systemLoad) { + this.systemLoad = systemLoad; + return this; + } + + /** + * Get the system load status. + * + * @return the systemLoadStatus value + */ + public String systemLoadStatus() { + return this.systemLoadStatus; + } + + /** + * Set the system load status. + * + * @param systemLoadStatus the systemLoadStatus value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withSystemLoadStatus(String systemLoadStatus) { + this.systemLoadStatus = systemLoadStatus; + return this; + } + + /** + * Get the percentage of the CPU load. + * + * @return the cpuLoad value + */ + public String cpuLoad() { + return this.cpuLoad; + } + + /** + * Set the percentage of the CPU load. + * + * @param cpuLoad the cpuLoad value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withCpuLoad(String cpuLoad) { + this.cpuLoad = cpuLoad; + return this; + } + + /** + * Get the CPU load status. + * + * @return the cpuLoadStatus value + */ + public String cpuLoadStatus() { + return this.cpuLoadStatus; + } + + /** + * Set the CPU load status. + * + * @param cpuLoadStatus the cpuLoadStatus value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withCpuLoadStatus(String cpuLoadStatus) { + this.cpuLoadStatus = cpuLoadStatus; + return this; + } + + /** + * Get the total memory. + * + * @return the totalMemoryInBytes value + */ + public Long totalMemoryInBytes() { + return this.totalMemoryInBytes; + } + + /** + * Set the total memory. + * + * @param totalMemoryInBytes the totalMemoryInBytes value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withTotalMemoryInBytes(Long totalMemoryInBytes) { + this.totalMemoryInBytes = totalMemoryInBytes; + return this; + } + + /** + * Get the available memory. + * + * @return the availableMemoryInBytes value + */ + public Long availableMemoryInBytes() { + return this.availableMemoryInBytes; + } + + /** + * Set the available memory. + * + * @param availableMemoryInBytes the availableMemoryInBytes value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withAvailableMemoryInBytes(Long availableMemoryInBytes) { + this.availableMemoryInBytes = availableMemoryInBytes; + return this; + } + + /** + * Get the memory usage status. + * + * @return the memoryUsageStatus value + */ + public String memoryUsageStatus() { + return this.memoryUsageStatus; + } + + /** + * Set the memory usage status. + * + * @param memoryUsageStatus the memoryUsageStatus value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withMemoryUsageStatus(String memoryUsageStatus) { + this.memoryUsageStatus = memoryUsageStatus; + return this; + } + + /** + * Get the total space. + * + * @return the totalSpaceInBytes value + */ + public Long totalSpaceInBytes() { + return this.totalSpaceInBytes; + } + + /** + * Set the total space. + * + * @param totalSpaceInBytes the totalSpaceInBytes value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withTotalSpaceInBytes(Long totalSpaceInBytes) { + this.totalSpaceInBytes = totalSpaceInBytes; + return this; + } + + /** + * Get the available space. + * + * @return the availableSpaceInBytes value + */ + public Long availableSpaceInBytes() { + return this.availableSpaceInBytes; + } + + /** + * Set the available space. + * + * @param availableSpaceInBytes the availableSpaceInBytes value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withAvailableSpaceInBytes(Long availableSpaceInBytes) { + this.availableSpaceInBytes = availableSpaceInBytes; + return this; + } + + /** + * Get the space usage status. + * + * @return the spaceUsageStatus value + */ + public String spaceUsageStatus() { + return this.spaceUsageStatus; + } + + /** + * Set the space usage status. + * + * @param spaceUsageStatus the spaceUsageStatus value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withSpaceUsageStatus(String spaceUsageStatus) { + this.spaceUsageStatus = spaceUsageStatus; + return this; + } + + /** + * Get the web load. + * + * @return the webLoad value + */ + public String webLoad() { + return this.webLoad; + } + + /** + * Set the web load. + * + * @param webLoad the webLoad value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withWebLoad(String webLoad) { + this.webLoad = webLoad; + return this; + } + + /** + * Get the web load status. + * + * @return the webLoadStatus value + */ + public String webLoadStatus() { + return this.webLoadStatus; + } + + /** + * Set the web load status. + * + * @param webLoadStatus the webLoadStatus value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withWebLoadStatus(String webLoadStatus) { + this.webLoadStatus = webLoadStatus; + return this; + } + + /** + * Get the database server load. + * + * @return the databaseServerLoad value + */ + public String databaseServerLoad() { + return this.databaseServerLoad; + } + + /** + * Set the database server load. + * + * @param databaseServerLoad the databaseServerLoad value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withDatabaseServerLoad(String databaseServerLoad) { + this.databaseServerLoad = databaseServerLoad; + return this; + } + + /** + * Get the database server load status. + * + * @return the databaseServerLoadStatus value + */ + public String databaseServerLoadStatus() { + return this.databaseServerLoadStatus; + } + + /** + * Set the database server load status. + * + * @param databaseServerLoadStatus the databaseServerLoadStatus value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withDatabaseServerLoadStatus(String databaseServerLoadStatus) { + this.databaseServerLoadStatus = databaseServerLoadStatus; + return this; + } + + /** + * Get the CS service status. + * + * @return the csServiceStatus value + */ + public String csServiceStatus() { + return this.csServiceStatus; + } + + /** + * Set the CS service status. + * + * @param csServiceStatus the csServiceStatus value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withCsServiceStatus(String csServiceStatus) { + this.csServiceStatus = csServiceStatus; + return this; + } + + /** + * Get the IP address. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the IP address. + * + * @param ipAddress the ipAddress value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the agent Version. + * + * @return the agentVersion value + */ + public String agentVersion() { + return this.agentVersion; + } + + /** + * Set the agent Version. + * + * @param agentVersion the agentVersion value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withAgentVersion(String agentVersion) { + this.agentVersion = agentVersion; + return this; + } + + /** + * Get the host name. + * + * @return the hostName value + */ + public String hostName() { + return this.hostName; + } + + /** + * Set the host name. + * + * @param hostName the hostName value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withHostName(String hostName) { + this.hostName = hostName; + return this; + } + + /** + * Get the last heartbeat received from CS server. + * + * @return the lastHeartbeat value + */ + public DateTime lastHeartbeat() { + return this.lastHeartbeat; + } + + /** + * Set the last heartbeat received from CS server. + * + * @param lastHeartbeat the lastHeartbeat value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withLastHeartbeat(DateTime lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + return this; + } + + /** + * Get version status. + * + * @return the versionStatus value + */ + public String versionStatus() { + return this.versionStatus; + } + + /** + * Set version status. + * + * @param versionStatus the versionStatus value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withVersionStatus(String versionStatus) { + this.versionStatus = versionStatus; + return this; + } + + /** + * Get cS SSL cert expiry date. + * + * @return the sslCertExpiryDate value + */ + public DateTime sslCertExpiryDate() { + return this.sslCertExpiryDate; + } + + /** + * Set cS SSL cert expiry date. + * + * @param sslCertExpiryDate the sslCertExpiryDate value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withSslCertExpiryDate(DateTime sslCertExpiryDate) { + this.sslCertExpiryDate = sslCertExpiryDate; + return this; + } + + /** + * Get cS SSL cert expiry date. + * + * @return the sslCertExpiryRemainingDays value + */ + public Integer sslCertExpiryRemainingDays() { + return this.sslCertExpiryRemainingDays; + } + + /** + * Set cS SSL cert expiry date. + * + * @param sslCertExpiryRemainingDays the sslCertExpiryRemainingDays value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withSslCertExpiryRemainingDays(Integer sslCertExpiryRemainingDays) { + this.sslCertExpiryRemainingDays = sslCertExpiryRemainingDays; + return this; + } + + /** + * Get pS template version. + * + * @return the psTemplateVersion value + */ + public String psTemplateVersion() { + return this.psTemplateVersion; + } + + /** + * Set pS template version. + * + * @param psTemplateVersion the psTemplateVersion value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withPsTemplateVersion(String psTemplateVersion) { + this.psTemplateVersion = psTemplateVersion; + return this; + } + + /** + * Get agent expiry date. + * + * @return the agentExpiryDate value + */ + public DateTime agentExpiryDate() { + return this.agentExpiryDate; + } + + /** + * Set agent expiry date. + * + * @param agentExpiryDate the agentExpiryDate value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withAgentExpiryDate(DateTime agentExpiryDate) { + this.agentExpiryDate = agentExpiryDate; + return this; + } + + /** + * Get the agent version details. + * + * @return the agentVersionDetails value + */ + public VersionDetails agentVersionDetails() { + return this.agentVersionDetails; + } + + /** + * Set the agent version details. + * + * @param agentVersionDetails the agentVersionDetails value to set + * @return the VMwareDetails object itself. + */ + public VMwareDetails withAgentVersionDetails(VersionDetails agentVersionDetails) { + this.agentVersionDetails = agentVersionDetails; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareV2FabricCreationInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareV2FabricCreationInput.java new file mode 100644 index 0000000000000..a6c2028382abe --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareV2FabricCreationInput.java @@ -0,0 +1,73 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareV2 fabric provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareV2") +public class VMwareV2FabricCreationInput extends FabricSpecificCreationInput { + /** + * The ARM Id of the VMware site. + */ + @JsonProperty(value = "vmwareSiteId", required = true) + private String vmwareSiteId; + + /** + * The ARM Id of the migration solution. + */ + @JsonProperty(value = "migrationSolutionId", required = true) + private String migrationSolutionId; + + /** + * Get the ARM Id of the VMware site. + * + * @return the vmwareSiteId value + */ + public String vmwareSiteId() { + return this.vmwareSiteId; + } + + /** + * Set the ARM Id of the VMware site. + * + * @param vmwareSiteId the vmwareSiteId value to set + * @return the VMwareV2FabricCreationInput object itself. + */ + public VMwareV2FabricCreationInput withVmwareSiteId(String vmwareSiteId) { + this.vmwareSiteId = vmwareSiteId; + return this; + } + + /** + * Get the ARM Id of the migration solution. + * + * @return the migrationSolutionId value + */ + public String migrationSolutionId() { + return this.migrationSolutionId; + } + + /** + * Set the ARM Id of the migration solution. + * + * @param migrationSolutionId the migrationSolutionId value to set + * @return the VMwareV2FabricCreationInput object itself. + */ + public VMwareV2FabricCreationInput withMigrationSolutionId(String migrationSolutionId) { + this.migrationSolutionId = migrationSolutionId; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareV2FabricSpecificDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareV2FabricSpecificDetails.java new file mode 100644 index 0000000000000..1ea4cfb47fc79 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareV2FabricSpecificDetails.java @@ -0,0 +1,66 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMwareV2 fabric specific details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareV2") +public class VMwareV2FabricSpecificDetails extends FabricSpecificDetails { + /** + * The ARM Id of the VMware site. + */ + @JsonProperty(value = "vmwareSiteId", access = JsonProperty.Access.WRITE_ONLY) + private String vmwareSiteId; + + /** + * The Migration solution ARM Id. + */ + @JsonProperty(value = "migrationSolutionId", access = JsonProperty.Access.WRITE_ONLY) + private String migrationSolutionId; + + /** + * The service endpoint. + */ + @JsonProperty(value = "serviceEndpoint", access = JsonProperty.Access.WRITE_ONLY) + private String serviceEndpoint; + + /** + * Get the ARM Id of the VMware site. + * + * @return the vmwareSiteId value + */ + public String vmwareSiteId() { + return this.vmwareSiteId; + } + + /** + * Get the Migration solution ARM Id. + * + * @return the migrationSolutionId value + */ + public String migrationSolutionId() { + return this.migrationSolutionId; + } + + /** + * Get the service endpoint. + * + * @return the serviceEndpoint value + */ + public String serviceEndpoint() { + return this.serviceEndpoint; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareVirtualMachineDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareVirtualMachineDetails.java new file mode 100644 index 0000000000000..34c91b10656b7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VMwareVirtualMachineDetails.java @@ -0,0 +1,284 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMware provider specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareVirtualMachine") +public class VMwareVirtualMachineDetails extends ConfigurationSettings { + /** + * The ID generated by the InMage agent after it gets installed on guest. + * This is the ID to be used during InMage CreateProtection. + */ + @JsonProperty(value = "agentGeneratedId") + private String agentGeneratedId; + + /** + * The value indicating if InMage scout agent is installed on guest. + */ + @JsonProperty(value = "agentInstalled") + private String agentInstalled; + + /** + * The OsType installed on VM. + */ + @JsonProperty(value = "osType") + private String osType; + + /** + * The agent version. + */ + @JsonProperty(value = "agentVersion") + private String agentVersion; + + /** + * The IP address. + */ + @JsonProperty(value = "ipAddress") + private String ipAddress; + + /** + * The value indicating whether VM is powered on. + */ + @JsonProperty(value = "poweredOn") + private String poweredOn; + + /** + * The VCenter infrastructure Id. + */ + @JsonProperty(value = "vCenterInfrastructureId") + private String vCenterInfrastructureId; + + /** + * A value indicating the discovery type of the machine. Value can be + * vCenter or physical. + */ + @JsonProperty(value = "discoveryType") + private String discoveryType; + + /** + * The disk details. + */ + @JsonProperty(value = "diskDetails") + private List diskDetails; + + /** + * The validation errors. + */ + @JsonProperty(value = "validationErrors") + private List validationErrors; + + /** + * Get the ID generated by the InMage agent after it gets installed on guest. This is the ID to be used during InMage CreateProtection. + * + * @return the agentGeneratedId value + */ + public String agentGeneratedId() { + return this.agentGeneratedId; + } + + /** + * Set the ID generated by the InMage agent after it gets installed on guest. This is the ID to be used during InMage CreateProtection. + * + * @param agentGeneratedId the agentGeneratedId value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withAgentGeneratedId(String agentGeneratedId) { + this.agentGeneratedId = agentGeneratedId; + return this; + } + + /** + * Get the value indicating if InMage scout agent is installed on guest. + * + * @return the agentInstalled value + */ + public String agentInstalled() { + return this.agentInstalled; + } + + /** + * Set the value indicating if InMage scout agent is installed on guest. + * + * @param agentInstalled the agentInstalled value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withAgentInstalled(String agentInstalled) { + this.agentInstalled = agentInstalled; + return this; + } + + /** + * Get the OsType installed on VM. + * + * @return the osType value + */ + public String osType() { + return this.osType; + } + + /** + * Set the OsType installed on VM. + * + * @param osType the osType value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withOsType(String osType) { + this.osType = osType; + return this; + } + + /** + * Get the agent version. + * + * @return the agentVersion value + */ + public String agentVersion() { + return this.agentVersion; + } + + /** + * Set the agent version. + * + * @param agentVersion the agentVersion value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withAgentVersion(String agentVersion) { + this.agentVersion = agentVersion; + return this; + } + + /** + * Get the IP address. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Set the IP address. + * + * @param ipAddress the ipAddress value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * Get the value indicating whether VM is powered on. + * + * @return the poweredOn value + */ + public String poweredOn() { + return this.poweredOn; + } + + /** + * Set the value indicating whether VM is powered on. + * + * @param poweredOn the poweredOn value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withPoweredOn(String poweredOn) { + this.poweredOn = poweredOn; + return this; + } + + /** + * Get the VCenter infrastructure Id. + * + * @return the vCenterInfrastructureId value + */ + public String vCenterInfrastructureId() { + return this.vCenterInfrastructureId; + } + + /** + * Set the VCenter infrastructure Id. + * + * @param vCenterInfrastructureId the vCenterInfrastructureId value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withVCenterInfrastructureId(String vCenterInfrastructureId) { + this.vCenterInfrastructureId = vCenterInfrastructureId; + return this; + } + + /** + * Get a value indicating the discovery type of the machine. Value can be vCenter or physical. + * + * @return the discoveryType value + */ + public String discoveryType() { + return this.discoveryType; + } + + /** + * Set a value indicating the discovery type of the machine. Value can be vCenter or physical. + * + * @param discoveryType the discoveryType value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withDiscoveryType(String discoveryType) { + this.discoveryType = discoveryType; + return this; + } + + /** + * Get the disk details. + * + * @return the diskDetails value + */ + public List diskDetails() { + return this.diskDetails; + } + + /** + * Set the disk details. + * + * @param diskDetails the diskDetails value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withDiskDetails(List diskDetails) { + this.diskDetails = diskDetails; + return this; + } + + /** + * Get the validation errors. + * + * @return the validationErrors value + */ + public List validationErrors() { + return this.validationErrors; + } + + /** + * Set the validation errors. + * + * @param validationErrors the validationErrors value to set + * @return the VMwareVirtualMachineDetails object itself. + */ + public VMwareVirtualMachineDetails withValidationErrors(List validationErrors) { + this.validationErrors = validationErrors; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VaultHealthDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VaultHealthDetails.java new file mode 100644 index 0000000000000..c880cb3f7fcc7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VaultHealthDetails.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.RecoveryServicesManager; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation.VaultHealthDetailsInner; + +/** + * Type representing VaultHealthDetails. + */ +public interface VaultHealthDetails extends HasInner, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the properties value. + */ + VaultHealthProperties properties(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VaultHealthProperties.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VaultHealthProperties.java new file mode 100644 index 0000000000000..3506b388fef15 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VaultHealthProperties.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * class to define the health summary of the Vault. + */ +public class VaultHealthProperties { + /** + * The list of errors on the vault. + */ + @JsonProperty(value = "vaultErrors") + private List vaultErrors; + + /** + * The list of the health detail of the protected items in the vault. + */ + @JsonProperty(value = "protectedItemsHealth") + private ResourceHealthSummary protectedItemsHealth; + + /** + * The list of the health detail of the fabrics in the vault. + */ + @JsonProperty(value = "fabricsHealth") + private ResourceHealthSummary fabricsHealth; + + /** + * The list of the health detail of the containers in the vault. + */ + @JsonProperty(value = "containersHealth") + private ResourceHealthSummary containersHealth; + + /** + * Get the list of errors on the vault. + * + * @return the vaultErrors value + */ + public List vaultErrors() { + return this.vaultErrors; + } + + /** + * Set the list of errors on the vault. + * + * @param vaultErrors the vaultErrors value to set + * @return the VaultHealthProperties object itself. + */ + public VaultHealthProperties withVaultErrors(List vaultErrors) { + this.vaultErrors = vaultErrors; + return this; + } + + /** + * Get the list of the health detail of the protected items in the vault. + * + * @return the protectedItemsHealth value + */ + public ResourceHealthSummary protectedItemsHealth() { + return this.protectedItemsHealth; + } + + /** + * Set the list of the health detail of the protected items in the vault. + * + * @param protectedItemsHealth the protectedItemsHealth value to set + * @return the VaultHealthProperties object itself. + */ + public VaultHealthProperties withProtectedItemsHealth(ResourceHealthSummary protectedItemsHealth) { + this.protectedItemsHealth = protectedItemsHealth; + return this; + } + + /** + * Get the list of the health detail of the fabrics in the vault. + * + * @return the fabricsHealth value + */ + public ResourceHealthSummary fabricsHealth() { + return this.fabricsHealth; + } + + /** + * Set the list of the health detail of the fabrics in the vault. + * + * @param fabricsHealth the fabricsHealth value to set + * @return the VaultHealthProperties object itself. + */ + public VaultHealthProperties withFabricsHealth(ResourceHealthSummary fabricsHealth) { + this.fabricsHealth = fabricsHealth; + return this; + } + + /** + * Get the list of the health detail of the containers in the vault. + * + * @return the containersHealth value + */ + public ResourceHealthSummary containersHealth() { + return this.containersHealth; + } + + /** + * Set the list of the health detail of the containers in the vault. + * + * @param containersHealth the containersHealth value to set + * @return the VaultHealthProperties object itself. + */ + public VaultHealthProperties withContainersHealth(ResourceHealthSummary containersHealth) { + this.containersHealth = containersHealth; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VersionDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VersionDetails.java new file mode 100644 index 0000000000000..be02b05097da0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VersionDetails.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Version related details. + */ +public class VersionDetails { + /** + * The agent version. + */ + @JsonProperty(value = "version") + private String version; + + /** + * Version expiry date. + */ + @JsonProperty(value = "expiryDate") + private DateTime expiryDate; + + /** + * A value indicating whether security update required. Possible values + * include: 'Supported', 'NotSupported', 'Deprecated', 'UpdateRequired', + * 'SecurityUpdateRequired'. + */ + @JsonProperty(value = "status") + private AgentVersionStatus status; + + /** + * Get the agent version. + * + * @return the version value + */ + public String version() { + return this.version; + } + + /** + * Set the agent version. + * + * @param version the version value to set + * @return the VersionDetails object itself. + */ + public VersionDetails withVersion(String version) { + this.version = version; + return this; + } + + /** + * Get version expiry date. + * + * @return the expiryDate value + */ + public DateTime expiryDate() { + return this.expiryDate; + } + + /** + * Set version expiry date. + * + * @param expiryDate the expiryDate value to set + * @return the VersionDetails object itself. + */ + public VersionDetails withExpiryDate(DateTime expiryDate) { + this.expiryDate = expiryDate; + return this; + } + + /** + * Get a value indicating whether security update required. Possible values include: 'Supported', 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'. + * + * @return the status value + */ + public AgentVersionStatus status() { + return this.status; + } + + /** + * Set a value indicating whether security update required. Possible values include: 'Supported', 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'. + * + * @param status the status value to set + * @return the VersionDetails object itself. + */ + public VersionDetails withStatus(AgentVersionStatus status) { + this.status = status; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VirtualMachineTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VirtualMachineTaskDetails.java new file mode 100644 index 0000000000000..b1ebf0ad5649c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VirtualMachineTaskDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the virtual machine task details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VirtualMachineTaskDetails") +public class VirtualMachineTaskDetails extends TaskTypeDetails { + /** + * The skipped reason. + */ + @JsonProperty(value = "skippedReason") + private String skippedReason; + + /** + * The skipped reason string. + */ + @JsonProperty(value = "skippedReasonString") + private String skippedReasonString; + + /** + * The job entity. + */ + @JsonProperty(value = "jobTask") + private JobEntity jobTask; + + /** + * Get the skipped reason. + * + * @return the skippedReason value + */ + public String skippedReason() { + return this.skippedReason; + } + + /** + * Set the skipped reason. + * + * @param skippedReason the skippedReason value to set + * @return the VirtualMachineTaskDetails object itself. + */ + public VirtualMachineTaskDetails withSkippedReason(String skippedReason) { + this.skippedReason = skippedReason; + return this; + } + + /** + * Get the skipped reason string. + * + * @return the skippedReasonString value + */ + public String skippedReasonString() { + return this.skippedReasonString; + } + + /** + * Set the skipped reason string. + * + * @param skippedReasonString the skippedReasonString value to set + * @return the VirtualMachineTaskDetails object itself. + */ + public VirtualMachineTaskDetails withSkippedReasonString(String skippedReasonString) { + this.skippedReasonString = skippedReasonString; + return this; + } + + /** + * Get the job entity. + * + * @return the jobTask value + */ + public JobEntity jobTask() { + return this.jobTask; + } + + /** + * Set the job entity. + * + * @param jobTask the jobTask value to set + * @return the VirtualMachineTaskDetails object itself. + */ + public VirtualMachineTaskDetails withJobTask(JobEntity jobTask) { + this.jobTask = jobTask; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmNicUpdatesTaskDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmNicUpdatesTaskDetails.java new file mode 100644 index 0000000000000..479345a71dcbc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmNicUpdatesTaskDetails.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * This class represents the vm NicUpdates task details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VmNicUpdatesTaskDetails") +public class VmNicUpdatesTaskDetails extends TaskTypeDetails { + /** + * Virtual machine Id. + */ + @JsonProperty(value = "vmId") + private String vmId; + + /** + * Nic Id. + */ + @JsonProperty(value = "nicId") + private String nicId; + + /** + * Name of the Nic. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Get virtual machine Id. + * + * @return the vmId value + */ + public String vmId() { + return this.vmId; + } + + /** + * Set virtual machine Id. + * + * @param vmId the vmId value to set + * @return the VmNicUpdatesTaskDetails object itself. + */ + public VmNicUpdatesTaskDetails withVmId(String vmId) { + this.vmId = vmId; + return this; + } + + /** + * Get nic Id. + * + * @return the nicId value + */ + public String nicId() { + return this.nicId; + } + + /** + * Set nic Id. + * + * @param nicId the nicId value to set + * @return the VmNicUpdatesTaskDetails object itself. + */ + public VmNicUpdatesTaskDetails withNicId(String nicId) { + this.nicId = nicId; + return this; + } + + /** + * Get name of the Nic. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set name of the Nic. + * + * @param name the name value to set + * @return the VmNicUpdatesTaskDetails object itself. + */ + public VmNicUpdatesTaskDetails withName(String name) { + this.name = name; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmDetails.java new file mode 100644 index 0000000000000..68a533bdaeddd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmDetails.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMM fabric specific details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMM") +public class VmmDetails extends FabricSpecificDetails { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureCreateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureCreateNetworkMappingInput.java new file mode 100644 index 0000000000000..a056a3d5a8d97 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureCreateNetworkMappingInput.java @@ -0,0 +1,21 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Create network mappings input properties/behavior specific to Vmm to Azure + * Network mapping. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VmmToAzure") +public class VmmToAzureCreateNetworkMappingInput extends FabricSpecificCreateNetworkMappingInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureNetworkMappingSettings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureNetworkMappingSettings.java new file mode 100644 index 0000000000000..f29358d714040 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureNetworkMappingSettings.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * E2A Network Mapping fabric specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VmmToAzure") +public class VmmToAzureNetworkMappingSettings extends NetworkMappingFabricSpecificSettings { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureUpdateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureUpdateNetworkMappingInput.java new file mode 100644 index 0000000000000..0e42ac5ef8675 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToAzureUpdateNetworkMappingInput.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Update network mappings input properties/behavior specific to vmm to azure. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VmmToAzure") +public class VmmToAzureUpdateNetworkMappingInput extends FabricSpecificUpdateNetworkMappingInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmCreateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmCreateNetworkMappingInput.java new file mode 100644 index 0000000000000..0431eb03b2e37 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmCreateNetworkMappingInput.java @@ -0,0 +1,21 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Create network mappings input properties/behavior specific to vmm to vmm + * Network mapping. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VmmToVmm") +public class VmmToVmmCreateNetworkMappingInput extends FabricSpecificCreateNetworkMappingInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmNetworkMappingSettings.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmNetworkMappingSettings.java new file mode 100644 index 0000000000000..5ac13a94e9dd2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmNetworkMappingSettings.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * E2E Network Mapping fabric specific settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VmmToVmm") +public class VmmToVmmNetworkMappingSettings extends NetworkMappingFabricSpecificSettings { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmUpdateNetworkMappingInput.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmUpdateNetworkMappingInput.java new file mode 100644 index 0000000000000..c3e17206ae570 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmToVmmUpdateNetworkMappingInput.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Update network mappings input properties/behavior specific to vmm to vmm. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VmmToVmm") +public class VmmToVmmUpdateNetworkMappingInput extends FabricSpecificUpdateNetworkMappingInput { +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmVirtualMachineDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmVirtualMachineDetails.java new file mode 100644 index 0000000000000..f8fbb9eb1ba11 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmmVirtualMachineDetails.java @@ -0,0 +1,210 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMM fabric provider specific VM settings. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VmmVirtualMachine") +public class VmmVirtualMachineDetails extends ConfigurationSettings { + /** + * The source id of the object. + */ + @JsonProperty(value = "sourceItemId") + private String sourceItemId; + + /** + * The id of the object in fabric. + */ + @JsonProperty(value = "generation") + private String generation; + + /** + * The Last replication time. + */ + @JsonProperty(value = "osDetails") + private OSDetails osDetails; + + /** + * The Last successful failover time. + */ + @JsonProperty(value = "diskDetails") + private List diskDetails; + + /** + * A value indicating whether the VM has a physical disk attached. String + * value of {SrsDataContract.PresenceStatus} enum. Possible values include: + * 'Unknown', 'Present', 'NotPresent'. + */ + @JsonProperty(value = "hasPhysicalDisk") + private PresenceStatus hasPhysicalDisk; + + /** + * A value indicating whether the VM has a fibre channel adapter attached. + * String value of {SrsDataContract.PresenceStatus} enum. Possible values + * include: 'Unknown', 'Present', 'NotPresent'. + */ + @JsonProperty(value = "hasFibreChannelAdapter") + private PresenceStatus hasFibreChannelAdapter; + + /** + * A value indicating whether the VM has a shared VHD attached. String + * value of {SrsDataContract.PresenceStatus} enum. Possible values include: + * 'Unknown', 'Present', 'NotPresent'. + */ + @JsonProperty(value = "hasSharedVhd") + private PresenceStatus hasSharedVhd; + + /** + * Get the source id of the object. + * + * @return the sourceItemId value + */ + public String sourceItemId() { + return this.sourceItemId; + } + + /** + * Set the source id of the object. + * + * @param sourceItemId the sourceItemId value to set + * @return the VmmVirtualMachineDetails object itself. + */ + public VmmVirtualMachineDetails withSourceItemId(String sourceItemId) { + this.sourceItemId = sourceItemId; + return this; + } + + /** + * Get the id of the object in fabric. + * + * @return the generation value + */ + public String generation() { + return this.generation; + } + + /** + * Set the id of the object in fabric. + * + * @param generation the generation value to set + * @return the VmmVirtualMachineDetails object itself. + */ + public VmmVirtualMachineDetails withGeneration(String generation) { + this.generation = generation; + return this; + } + + /** + * Get the Last replication time. + * + * @return the osDetails value + */ + public OSDetails osDetails() { + return this.osDetails; + } + + /** + * Set the Last replication time. + * + * @param osDetails the osDetails value to set + * @return the VmmVirtualMachineDetails object itself. + */ + public VmmVirtualMachineDetails withOsDetails(OSDetails osDetails) { + this.osDetails = osDetails; + return this; + } + + /** + * Get the Last successful failover time. + * + * @return the diskDetails value + */ + public List diskDetails() { + return this.diskDetails; + } + + /** + * Set the Last successful failover time. + * + * @param diskDetails the diskDetails value to set + * @return the VmmVirtualMachineDetails object itself. + */ + public VmmVirtualMachineDetails withDiskDetails(List diskDetails) { + this.diskDetails = diskDetails; + return this; + } + + /** + * Get a value indicating whether the VM has a physical disk attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @return the hasPhysicalDisk value + */ + public PresenceStatus hasPhysicalDisk() { + return this.hasPhysicalDisk; + } + + /** + * Set a value indicating whether the VM has a physical disk attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @param hasPhysicalDisk the hasPhysicalDisk value to set + * @return the VmmVirtualMachineDetails object itself. + */ + public VmmVirtualMachineDetails withHasPhysicalDisk(PresenceStatus hasPhysicalDisk) { + this.hasPhysicalDisk = hasPhysicalDisk; + return this; + } + + /** + * Get a value indicating whether the VM has a fibre channel adapter attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @return the hasFibreChannelAdapter value + */ + public PresenceStatus hasFibreChannelAdapter() { + return this.hasFibreChannelAdapter; + } + + /** + * Set a value indicating whether the VM has a fibre channel adapter attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @param hasFibreChannelAdapter the hasFibreChannelAdapter value to set + * @return the VmmVirtualMachineDetails object itself. + */ + public VmmVirtualMachineDetails withHasFibreChannelAdapter(PresenceStatus hasFibreChannelAdapter) { + this.hasFibreChannelAdapter = hasFibreChannelAdapter; + return this; + } + + /** + * Get a value indicating whether the VM has a shared VHD attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @return the hasSharedVhd value + */ + public PresenceStatus hasSharedVhd() { + return this.hasSharedVhd; + } + + /** + * Set a value indicating whether the VM has a shared VHD attached. String value of {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown', 'Present', 'NotPresent'. + * + * @param hasSharedVhd the hasSharedVhd value to set + * @return the VmmVirtualMachineDetails object itself. + */ + public VmmVirtualMachineDetails withHasSharedVhd(PresenceStatus hasSharedVhd) { + this.hasSharedVhd = hasSharedVhd; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmwareCbtPolicyDetails.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmwareCbtPolicyDetails.java new file mode 100644 index 0000000000000..81bf2c5d6821c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/VmwareCbtPolicyDetails.java @@ -0,0 +1,100 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * VMware Cbt specific policy details. + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType") +@JsonTypeName("VMwareCbt") +public class VmwareCbtPolicyDetails extends PolicyProviderSpecificDetails { + /** + * The duration in minutes until which the recovery points need to be + * stored. + */ + @JsonProperty(value = "recoveryPointHistoryInMinutes") + private Integer recoveryPointHistoryInMinutes; + + /** + * The app consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "appConsistentFrequencyInMinutes") + private Integer appConsistentFrequencyInMinutes; + + /** + * The crash consistent snapshot frequency in minutes. + */ + @JsonProperty(value = "crashConsistentFrequencyInMinutes") + private Integer crashConsistentFrequencyInMinutes; + + /** + * Get the duration in minutes until which the recovery points need to be stored. + * + * @return the recoveryPointHistoryInMinutes value + */ + public Integer recoveryPointHistoryInMinutes() { + return this.recoveryPointHistoryInMinutes; + } + + /** + * Set the duration in minutes until which the recovery points need to be stored. + * + * @param recoveryPointHistoryInMinutes the recoveryPointHistoryInMinutes value to set + * @return the VmwareCbtPolicyDetails object itself. + */ + public VmwareCbtPolicyDetails withRecoveryPointHistoryInMinutes(Integer recoveryPointHistoryInMinutes) { + this.recoveryPointHistoryInMinutes = recoveryPointHistoryInMinutes; + return this; + } + + /** + * Get the app consistent snapshot frequency in minutes. + * + * @return the appConsistentFrequencyInMinutes value + */ + public Integer appConsistentFrequencyInMinutes() { + return this.appConsistentFrequencyInMinutes; + } + + /** + * Set the app consistent snapshot frequency in minutes. + * + * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set + * @return the VmwareCbtPolicyDetails object itself. + */ + public VmwareCbtPolicyDetails withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) { + this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes; + return this; + } + + /** + * Get the crash consistent snapshot frequency in minutes. + * + * @return the crashConsistentFrequencyInMinutes value + */ + public Integer crashConsistentFrequencyInMinutes() { + return this.crashConsistentFrequencyInMinutes; + } + + /** + * Set the crash consistent snapshot frequency in minutes. + * + * @param crashConsistentFrequencyInMinutes the crashConsistentFrequencyInMinutes value to set + * @return the VmwareCbtPolicyDetails object itself. + */ + public VmwareCbtPolicyDetails withCrashConsistentFrequencyInMinutes(Integer crashConsistentFrequencyInMinutes) { + this.crashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/AlertImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/AlertImpl.java new file mode 100644 index 0000000000000..dba9cd944aacc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/AlertImpl.java @@ -0,0 +1,136 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Alert; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ConfigureAlertRequestProperties; +import java.util.List; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.AlertProperties; +import rx.functions.Func1; + +class AlertImpl extends CreatableUpdatableImpl implements Alert, Alert.Definition, Alert.Update { + private final RecoveryServicesManager manager; + private String alertSettingName; + private ConfigureAlertRequestProperties cproperties; + private ConfigureAlertRequestProperties uproperties; + + AlertImpl(String name, RecoveryServicesManager manager) { + super(name, new AlertInner()); + this.manager = manager; + // Set resource name + this.alertSettingName = name; + // + this.cproperties = new ConfigureAlertRequestProperties(); + this.uproperties = new ConfigureAlertRequestProperties(); + } + + AlertImpl(AlertInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.alertSettingName = inner.name(); + // set resource ancestor and positional variables + this.alertSettingName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationAlertSettings"); + // + this.cproperties = new ConfigureAlertRequestProperties(); + this.uproperties = new ConfigureAlertRequestProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationAlertSettingsInner client = this.manager().inner().replicationAlertSettings(); + return client.createAsync(this.alertSettingName, this.cproperties) + .map(new Func1() { + @Override + public AlertInner call(AlertInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationAlertSettingsInner client = this.manager().inner().replicationAlertSettings(); + return client.createAsync(this.alertSettingName, this.uproperties) + .map(new Func1() { + @Override + public AlertInner call(AlertInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationAlertSettingsInner client = this.manager().inner().replicationAlertSettings(); + return client.getAsync(this.alertSettingName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new ConfigureAlertRequestProperties(); + this.uproperties = new ConfigureAlertRequestProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public AlertProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public AlertImpl withExistingVault() { + return this; + } + + @Override + public AlertImpl withProperties(ConfigureAlertRequestProperties properties) { + if (isInCreateMode()) { + this.cproperties = properties; + } else { + this.uproperties = properties; + } + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/AlertInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/AlertInner.java new file mode 100644 index 0000000000000..d52c77c558e27 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/AlertInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.AlertProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Implements the Alert class. + */ +public class AlertInner extends ProxyResource { + /** + * Alert related data. + */ + @JsonProperty(value = "properties") + private AlertProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get alert related data. + * + * @return the properties value + */ + public AlertProperties properties() { + return this.properties; + } + + /** + * Set alert related data. + * + * @param properties the properties value to set + * @return the AlertInner object itself. + */ + public AlertInner withProperties(AlertProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the AlertInner object itself. + */ + public AlertInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/EventImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/EventImpl.java new file mode 100644 index 0000000000000..41cbe111e7fb8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/EventImpl.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Event; +import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EventProperties; + +class EventImpl extends IndexableRefreshableWrapperImpl implements Event { + private final RecoveryServicesManager manager; + private String eventName; + + EventImpl(EventInner inner, RecoveryServicesManager manager) { + super(null, inner); + this.manager = manager; + // set resource ancestor and positional variables + this.eventName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationEvents"); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + protected Observable getInnerAsync() { + ReplicationEventsInner client = this.manager().inner().replicationEvents(); + return client.getAsync(this.eventName); + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public EventProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/EventInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/EventInner.java new file mode 100644 index 0000000000000..562e27d7980fd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/EventInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EventProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Implements the Event class. + */ +public class EventInner extends ProxyResource { + /** + * Event related data. + */ + @JsonProperty(value = "properties") + private EventProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get event related data. + * + * @return the properties value + */ + public EventProperties properties() { + return this.properties; + } + + /** + * Set event related data. + * + * @param properties the properties value to set + * @return the EventInner object itself. + */ + public EventInner withProperties(EventProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the EventInner object itself. + */ + public EventInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/FabricImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/FabricImpl.java new file mode 100644 index 0000000000000..9009f3b3ca29b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/FabricImpl.java @@ -0,0 +1,135 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Fabric; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.FabricCreationInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.FabricProperties; +import rx.functions.Func1; + +class FabricImpl extends CreatableUpdatableImpl implements Fabric, Fabric.Definition, Fabric.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private FabricCreationInputProperties cproperties; + private FabricCreationInputProperties uproperties; + + FabricImpl(String name, RecoveryServicesManager manager) { + super(name, new FabricInner()); + this.manager = manager; + // Set resource name + this.fabricName = name; + // + this.cproperties = new FabricCreationInputProperties(); + this.uproperties = new FabricCreationInputProperties(); + } + + FabricImpl(FabricInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.fabricName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + // + this.cproperties = new FabricCreationInputProperties(); + this.uproperties = new FabricCreationInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationFabricsInner client = this.manager().inner().replicationFabrics(); + return client.createAsync(this.fabricName, this.cproperties) + .map(new Func1() { + @Override + public FabricInner call(FabricInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationFabricsInner client = this.manager().inner().replicationFabrics(); + return client.createAsync(this.fabricName, this.uproperties) + .map(new Func1() { + @Override + public FabricInner call(FabricInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationFabricsInner client = this.manager().inner().replicationFabrics(); + return client.getAsync(this.fabricName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new FabricCreationInputProperties(); + this.uproperties = new FabricCreationInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public FabricProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public FabricImpl withExistingVault() { + return this; + } + + @Override + public FabricImpl withProperties(FabricCreationInputProperties properties) { + if (isInCreateMode()) { + this.cproperties = properties; + } else { + this.uproperties = properties; + } + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/FabricInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/FabricInner.java new file mode 100644 index 0000000000000..b208ad785dd12 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/FabricInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.FabricProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Fabric definition. + */ +public class FabricInner extends ProxyResource { + /** + * Fabric related data. + */ + @JsonProperty(value = "properties") + private FabricProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get fabric related data. + * + * @return the properties value + */ + public FabricProperties properties() { + return this.properties; + } + + /** + * Set fabric related data. + * + * @param properties the properties value to set + * @return the FabricInner object itself. + */ + public FabricInner withProperties(FabricProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the FabricInner object itself. + */ + public FabricInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/IdParsingUtils.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/IdParsingUtils.java new file mode 100644 index 0000000000000..c798f6ed7cf8f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/IdParsingUtils.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; +import java.util.Arrays; +import java.util.Iterator; + +class IdParsingUtils { + public static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + public static String getValueFromIdByPosition(String id, int pos) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + int index = 0; + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (index == pos) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + index++; + } + return null; + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/JobImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/JobImpl.java new file mode 100644 index 0000000000000..76cf9d8a81892 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/JobImpl.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Job; +import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.JobProperties; + +class JobImpl extends IndexableRefreshableWrapperImpl implements Job { + private final RecoveryServicesManager manager; + private String jobName; + + JobImpl(JobInner inner, RecoveryServicesManager manager) { + super(null, inner); + this.manager = manager; + // set resource ancestor and positional variables + this.jobName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationJobs"); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + protected Observable getInnerAsync() { + ReplicationJobsInner client = this.manager().inner().replicationJobs(); + return client.getAsync(this.jobName); + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public JobProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/JobInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/JobInner.java new file mode 100644 index 0000000000000..a1f0f86a452e9 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/JobInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.JobProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Job details. + */ +public class JobInner extends ProxyResource { + /** + * The custom data. + */ + @JsonProperty(value = "properties") + private JobProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the custom data. + * + * @return the properties value + */ + public JobProperties properties() { + return this.properties; + } + + /** + * Set the custom data. + * + * @param properties the properties value to set + * @return the JobInner object itself. + */ + public JobInner withProperties(JobProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the JobInner object itself. + */ + public JobInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/LogicalNetworkImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/LogicalNetworkImpl.java new file mode 100644 index 0000000000000..adcf7cd24c884 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/LogicalNetworkImpl.java @@ -0,0 +1,67 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.LogicalNetwork; +import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.LogicalNetworkProperties; + +class LogicalNetworkImpl extends IndexableRefreshableWrapperImpl implements LogicalNetwork { + private final RecoveryServicesManager manager; + private String fabricName; + private String logicalNetworkName; + + LogicalNetworkImpl(LogicalNetworkInner inner, RecoveryServicesManager manager) { + super(null, inner); + this.manager = manager; + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.logicalNetworkName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationLogicalNetworks"); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + protected Observable getInnerAsync() { + ReplicationLogicalNetworksInner client = this.manager().inner().replicationLogicalNetworks(); + return client.getAsync(this.fabricName, this.logicalNetworkName); + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public LogicalNetworkProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/LogicalNetworkInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/LogicalNetworkInner.java new file mode 100644 index 0000000000000..3f0dcf2ff35fb --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/LogicalNetworkInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.LogicalNetworkProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Logical network data model. + */ +public class LogicalNetworkInner extends ProxyResource { + /** + * The Logical Network Properties. + */ + @JsonProperty(value = "properties") + private LogicalNetworkProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the Logical Network Properties. + * + * @return the properties value + */ + public LogicalNetworkProperties properties() { + return this.properties; + } + + /** + * Set the Logical Network Properties. + * + * @param properties the properties value to set + * @return the LogicalNetworkInner object itself. + */ + public LogicalNetworkInner withProperties(LogicalNetworkProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the LogicalNetworkInner object itself. + */ + public LogicalNetworkInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationItemImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationItemImpl.java new file mode 100644 index 0000000000000..4fc088d9cd667 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationItemImpl.java @@ -0,0 +1,144 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationItem; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateMigrationItemInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EnableMigrationInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationItemProperties; +import rx.functions.Func1; + +class MigrationItemImpl extends CreatableUpdatableImpl implements MigrationItem, MigrationItem.Definition, MigrationItem.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private String protectionContainerName; + private String migrationItemName; + private EnableMigrationInputProperties cproperties; + private UpdateMigrationItemInputProperties uproperties; + + MigrationItemImpl(String name, RecoveryServicesManager manager) { + super(name, new MigrationItemInner()); + this.manager = manager; + // Set resource name + this.migrationItemName = name; + // + this.cproperties = new EnableMigrationInputProperties(); + this.uproperties = new UpdateMigrationItemInputProperties(); + } + + MigrationItemImpl(MigrationItemInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.migrationItemName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.protectionContainerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainers"); + this.migrationItemName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationMigrationItems"); + // + this.cproperties = new EnableMigrationInputProperties(); + this.uproperties = new UpdateMigrationItemInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationMigrationItemsInner client = this.manager().inner().replicationMigrationItems(); + return client.createAsync(this.fabricName, this.protectionContainerName, this.migrationItemName, this.cproperties) + .map(new Func1() { + @Override + public MigrationItemInner call(MigrationItemInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationMigrationItemsInner client = this.manager().inner().replicationMigrationItems(); + return client.updateAsync(this.fabricName, this.protectionContainerName, this.migrationItemName, this.uproperties) + .map(new Func1() { + @Override + public MigrationItemInner call(MigrationItemInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationMigrationItemsInner client = this.manager().inner().replicationMigrationItems(); + return client.getAsync(this.fabricName, this.protectionContainerName, this.migrationItemName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new EnableMigrationInputProperties(); + this.uproperties = new UpdateMigrationItemInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public MigrationItemProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public MigrationItemImpl withExistingReplicationProtectionContainer(String fabricName, String protectionContainerName) { + this.fabricName = fabricName; + this.protectionContainerName = protectionContainerName; + return this; + } + + @Override + public MigrationItemImpl withProperties(EnableMigrationInputProperties properties) { + this.cproperties = properties; + return this; + } + + @Override + public MigrationItemImpl withProperties(UpdateMigrationItemInputProperties properties) { + this.uproperties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationItemInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationItemInner.java new file mode 100644 index 0000000000000..69a38011f0fc7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationItemInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationItemProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Migration item. + */ +public class MigrationItemInner extends ProxyResource { + /** + * The migration item properties. + */ + @JsonProperty(value = "properties") + private MigrationItemProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the migration item properties. + * + * @return the properties value + */ + public MigrationItemProperties properties() { + return this.properties; + } + + /** + * Set the migration item properties. + * + * @param properties the properties value to set + * @return the MigrationItemInner object itself. + */ + public MigrationItemInner withProperties(MigrationItemProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the MigrationItemInner object itself. + */ + public MigrationItemInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointImpl.java new file mode 100644 index 0000000000000..ef23a4e1a5698 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointImpl.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPoint; +import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPointProperties; + +class MigrationRecoveryPointImpl extends IndexableRefreshableWrapperImpl implements MigrationRecoveryPoint { + private final RecoveryServicesManager manager; + private String fabricName; + private String protectionContainerName; + private String migrationItemName; + private String migrationRecoveryPointName; + + MigrationRecoveryPointImpl(MigrationRecoveryPointInner inner, RecoveryServicesManager manager) { + super(null, inner); + this.manager = manager; + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.protectionContainerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainers"); + this.migrationItemName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationMigrationItems"); + this.migrationRecoveryPointName = IdParsingUtils.getValueFromIdByName(inner.id(), "migrationRecoveryPoints"); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + protected Observable getInnerAsync() { + MigrationRecoveryPointsInner client = this.manager().inner().migrationRecoveryPoints(); + return client.getAsync(this.fabricName, this.protectionContainerName, this.migrationItemName, this.migrationRecoveryPointName); + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public MigrationRecoveryPointProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointInner.java new file mode 100644 index 0000000000000..17f454c9b90b5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPointProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Recovery point for a migration item. + */ +public class MigrationRecoveryPointInner extends ProxyResource { + /** + * Recovery point properties. + */ + @JsonProperty(value = "properties") + private MigrationRecoveryPointProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get recovery point properties. + * + * @return the properties value + */ + public MigrationRecoveryPointProperties properties() { + return this.properties; + } + + /** + * Set recovery point properties. + * + * @param properties the properties value to set + * @return the MigrationRecoveryPointInner object itself. + */ + public MigrationRecoveryPointInner withProperties(MigrationRecoveryPointProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the MigrationRecoveryPointInner object itself. + */ + public MigrationRecoveryPointInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointsImpl.java new file mode 100644 index 0000000000000..bea06f712436d --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointsImpl.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPoints; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPoint; + +class MigrationRecoveryPointsImpl extends WrapperImpl implements MigrationRecoveryPoints { + private final RecoveryServicesManager manager; + + MigrationRecoveryPointsImpl(RecoveryServicesManager manager) { + super(manager.inner().migrationRecoveryPoints()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private MigrationRecoveryPointImpl wrapModel(MigrationRecoveryPointInner inner) { + return new MigrationRecoveryPointImpl(inner, manager()); + } + + @Override + public Observable listByReplicationMigrationItemsAsync(final String fabricName, final String protectionContainerName, final String migrationItemName) { + MigrationRecoveryPointsInner client = this.inner(); + return client.listByReplicationMigrationItemsAsync(fabricName, protectionContainerName, migrationItemName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public MigrationRecoveryPoint call(MigrationRecoveryPointInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String protectionContainerName, String migrationItemName, String migrationRecoveryPointName) { + MigrationRecoveryPointsInner client = this.inner(); + return client.getAsync(fabricName, protectionContainerName, migrationItemName, migrationRecoveryPointName) + .map(new Func1() { + @Override + public MigrationRecoveryPoint call(MigrationRecoveryPointInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointsInner.java new file mode 100644 index 0000000000000..8a85397331728 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/MigrationRecoveryPointsInner.java @@ -0,0 +1,428 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in MigrationRecoveryPoints. + */ +public class MigrationRecoveryPointsInner { + /** The Retrofit service to perform REST calls. */ + private MigrationRecoveryPointsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of MigrationRecoveryPointsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public MigrationRecoveryPointsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(MigrationRecoveryPointsService.class); + this.client = client; + } + + /** + * The interface defining all the services for MigrationRecoveryPoints to be + * used by Retrofit to perform actually REST calls. + */ + interface MigrationRecoveryPointsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPoints listByReplicationMigrationItems" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/migrationRecoveryPoints") + Observable> listByReplicationMigrationItems(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPoints get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/migrationRecoveryPoints/{migrationRecoveryPointName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Path("migrationRecoveryPointName") String migrationRecoveryPointName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPoints listByReplicationMigrationItemsNext" }) + @GET + Observable> listByReplicationMigrationItemsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the recovery points for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<MigrationRecoveryPointInner> object if successful. + */ + public PagedList listByReplicationMigrationItems(final String fabricName, final String protectionContainerName, final String migrationItemName) { + ServiceResponse> response = listByReplicationMigrationItemsSinglePageAsync(fabricName, protectionContainerName, migrationItemName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationMigrationItemsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the recovery points for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationMigrationItemsAsync(final String fabricName, final String protectionContainerName, final String migrationItemName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationMigrationItemsSinglePageAsync(fabricName, protectionContainerName, migrationItemName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationMigrationItemsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the recovery points for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationRecoveryPointInner> object + */ + public Observable> listByReplicationMigrationItemsAsync(final String fabricName, final String protectionContainerName, final String migrationItemName) { + return listByReplicationMigrationItemsWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the recovery points for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationRecoveryPointInner> object + */ + public Observable>> listByReplicationMigrationItemsWithServiceResponseAsync(final String fabricName, final String protectionContainerName, final String migrationItemName) { + return listByReplicationMigrationItemsSinglePageAsync(fabricName, protectionContainerName, migrationItemName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationMigrationItemsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the recovery points for a migration item. + * + ServiceResponse> * @param fabricName Fabric unique name. + ServiceResponse> * @param protectionContainerName Protection container name. + ServiceResponse> * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<MigrationRecoveryPointInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationMigrationItemsSinglePageAsync(final String fabricName, final String protectionContainerName, final String migrationItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationMigrationItems(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationMigrationItemsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationMigrationItemsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets a recovery point for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param migrationRecoveryPointName The migration recovery point name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationRecoveryPointInner object if successful. + */ + public MigrationRecoveryPointInner get(String fabricName, String protectionContainerName, String migrationItemName, String migrationRecoveryPointName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, migrationRecoveryPointName).toBlocking().single().body(); + } + + /** + * Gets a recovery point for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param migrationRecoveryPointName The migration recovery point name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String protectionContainerName, String migrationItemName, String migrationRecoveryPointName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, migrationRecoveryPointName), serviceCallback); + } + + /** + * Gets a recovery point for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param migrationRecoveryPointName The migration recovery point name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationRecoveryPointInner object + */ + public Observable getAsync(String fabricName, String protectionContainerName, String migrationItemName, String migrationRecoveryPointName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, migrationRecoveryPointName).map(new Func1, MigrationRecoveryPointInner>() { + @Override + public MigrationRecoveryPointInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets a recovery point for a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param migrationRecoveryPointName The migration recovery point name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationRecoveryPointInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, String migrationRecoveryPointName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (migrationRecoveryPointName == null) { + throw new IllegalArgumentException("Parameter migrationRecoveryPointName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, migrationRecoveryPointName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the recovery points for a migration item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<MigrationRecoveryPointInner> object if successful. + */ + public PagedList listByReplicationMigrationItemsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationMigrationItemsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationMigrationItemsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the recovery points for a migration item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationMigrationItemsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationMigrationItemsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationMigrationItemsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the recovery points for a migration item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationRecoveryPointInner> object + */ + public Observable> listByReplicationMigrationItemsNextAsync(final String nextPageLink) { + return listByReplicationMigrationItemsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the recovery points for a migration item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationRecoveryPointInner> object + */ + public Observable>> listByReplicationMigrationItemsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationMigrationItemsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationMigrationItemsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the recovery points for a migration item. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<MigrationRecoveryPointInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationMigrationItemsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationMigrationItemsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationMigrationItemsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationMigrationItemsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkImpl.java new file mode 100644 index 0000000000000..06f310b487e71 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkImpl.java @@ -0,0 +1,67 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Network; +import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.NetworkProperties; + +class NetworkImpl extends IndexableRefreshableWrapperImpl implements Network { + private final RecoveryServicesManager manager; + private String fabricName; + private String networkName; + + NetworkImpl(NetworkInner inner, RecoveryServicesManager manager) { + super(null, inner); + this.manager = manager; + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.networkName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationNetworks"); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + protected Observable getInnerAsync() { + ReplicationNetworksInner client = this.manager().inner().replicationNetworks(); + return client.getAsync(this.fabricName, this.networkName); + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public NetworkProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkInner.java new file mode 100644 index 0000000000000..645e8393f0e62 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.NetworkProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Network model. + */ +public class NetworkInner extends ProxyResource { + /** + * The Network Properties. + */ + @JsonProperty(value = "properties") + private NetworkProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the Network Properties. + * + * @return the properties value + */ + public NetworkProperties properties() { + return this.properties; + } + + /** + * Set the Network Properties. + * + * @param properties the properties value to set + * @return the NetworkInner object itself. + */ + public NetworkInner withProperties(NetworkProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the NetworkInner object itself. + */ + public NetworkInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkMappingImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkMappingImpl.java new file mode 100644 index 0000000000000..55cff81329b85 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkMappingImpl.java @@ -0,0 +1,144 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.NetworkMapping; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateNetworkMappingInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateNetworkMappingInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.NetworkMappingProperties; +import rx.functions.Func1; + +class NetworkMappingImpl extends CreatableUpdatableImpl implements NetworkMapping, NetworkMapping.Definition, NetworkMapping.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private String networkName; + private String networkMappingName; + private CreateNetworkMappingInputProperties cproperties; + private UpdateNetworkMappingInputProperties uproperties; + + NetworkMappingImpl(String name, RecoveryServicesManager manager) { + super(name, new NetworkMappingInner()); + this.manager = manager; + // Set resource name + this.networkMappingName = name; + // + this.cproperties = new CreateNetworkMappingInputProperties(); + this.uproperties = new UpdateNetworkMappingInputProperties(); + } + + NetworkMappingImpl(NetworkMappingInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.networkMappingName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.networkName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationNetworks"); + this.networkMappingName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationNetworkMappings"); + // + this.cproperties = new CreateNetworkMappingInputProperties(); + this.uproperties = new UpdateNetworkMappingInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationNetworkMappingsInner client = this.manager().inner().replicationNetworkMappings(); + return client.createAsync(this.fabricName, this.networkName, this.networkMappingName, this.cproperties) + .map(new Func1() { + @Override + public NetworkMappingInner call(NetworkMappingInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationNetworkMappingsInner client = this.manager().inner().replicationNetworkMappings(); + return client.updateAsync(this.fabricName, this.networkName, this.networkMappingName, this.uproperties) + .map(new Func1() { + @Override + public NetworkMappingInner call(NetworkMappingInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationNetworkMappingsInner client = this.manager().inner().replicationNetworkMappings(); + return client.getAsync(this.fabricName, this.networkName, this.networkMappingName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new CreateNetworkMappingInputProperties(); + this.uproperties = new UpdateNetworkMappingInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public NetworkMappingProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public NetworkMappingImpl withExistingReplicationNetwork(String fabricName, String networkName) { + this.fabricName = fabricName; + this.networkName = networkName; + return this; + } + + @Override + public NetworkMappingImpl withProperties(CreateNetworkMappingInputProperties properties) { + this.cproperties = properties; + return this; + } + + @Override + public NetworkMappingImpl withProperties(UpdateNetworkMappingInputProperties properties) { + this.uproperties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkMappingInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkMappingInner.java new file mode 100644 index 0000000000000..39f0716eafb1c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/NetworkMappingInner.java @@ -0,0 +1,76 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.NetworkMappingProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Network Mapping model. Ideally it should have been possible to inherit this + * class from prev version in InheritedModels as long as there is no difference + * in structure or method signature. Since there were no base Models for + * certain fields and methods viz NetworkMappingProperties and Load with + * required return type, the class has been introduced in its entirety with + * references to base models to facilitate extensions in subsequent versions. + */ +public class NetworkMappingInner extends ProxyResource { + /** + * The Network Mapping Properties. + */ + @JsonProperty(value = "properties") + private NetworkMappingProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the Network Mapping Properties. + * + * @return the properties value + */ + public NetworkMappingProperties properties() { + return this.properties; + } + + /** + * Set the Network Mapping Properties. + * + * @param properties the properties value to set + * @return the NetworkMappingInner object itself. + */ + public NetworkMappingInner withProperties(NetworkMappingProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the NetworkMappingInner object itself. + */ + public NetworkMappingInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsDiscoveryImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsDiscoveryImpl.java new file mode 100644 index 0000000000000..10f203c7666cd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsDiscoveryImpl.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.OperationsDiscovery; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Display; + +class OperationsDiscoveryImpl extends WrapperImpl implements OperationsDiscovery { + private final RecoveryServicesManager manager; + + OperationsDiscoveryImpl(OperationsDiscoveryInner inner, RecoveryServicesManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + + + @Override + public Display display() { + return this.inner().display(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String origin() { + return this.inner().origin(); + } + + @Override + public Object properties() { + return this.inner().properties(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsDiscoveryInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsDiscoveryInner.java new file mode 100644 index 0000000000000..5434c860a3bac --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsDiscoveryInner.java @@ -0,0 +1,142 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Display; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Operations discovery class. + */ +public class OperationsDiscoveryInner { + /** + * Name of the API. The name of the operation being performed on this + * particular object. It should match the action name that appears in RBAC + * / the event service. Examples of operations include: * + * Microsoft.Compute/virtualMachine/capture/action * + * Microsoft.Compute/virtualMachine/restart/action * + * Microsoft.Compute/virtualMachine/write * + * Microsoft.Compute/virtualMachine/read * + * Microsoft.Compute/virtualMachine/delete Each action should include, in + * order: (1) Resource Provider Namespace (2) Type hierarchy for which the + * action applies (e.g. server/databases for a SQL Azure database) (3) + * Read, Write, Action or Delete indicating which type applies. If it is a + * PUT/PATCH on a collection or named value, Write should be used. If it is + * a GET, Read should be used. If it is a DELETE, Delete should be used. If + * it is a POST, Action should be used. As a note: all resource providers + * would need to include the "{Resource Provider + * Namespace}/register/action" operation in their response. This API is + * used to register for their service, and should include details about the + * operation (e.g. a localized name for the resource provider + any special + * considerations like PII release). + */ + @JsonProperty(value = "name") + private String name; + + /** + * Object type. + */ + @JsonProperty(value = "display") + private Display display; + + /** + * Origin. The intended executor of the operation; governs the display of + * the operation in the RBAC UX and the audit logs UX. Default value is + * "user,system". + */ + @JsonProperty(value = "origin") + private String origin; + + /** + * Properties. Reserved for future use. + */ + @JsonProperty(value = "properties") + private Object properties; + + /** + * Get name of the API. The name of the operation being performed on this particular object. It should match the action name that appears in RBAC / the event service. Examples of operations include: * Microsoft.Compute/virtualMachine/capture/action * Microsoft.Compute/virtualMachine/restart/action * Microsoft.Compute/virtualMachine/write * Microsoft.Compute/virtualMachine/read * Microsoft.Compute/virtualMachine/delete Each action should include, in order: (1) Resource Provider Namespace (2) Type hierarchy for which the action applies (e.g. server/databases for a SQL Azure database) (3) Read, Write, Action or Delete indicating which type applies. If it is a PUT/PATCH on a collection or named value, Write should be used. If it is a GET, Read should be used. If it is a DELETE, Delete should be used. If it is a POST, Action should be used. As a note: all resource providers would need to include the "{Resource Provider Namespace}/register/action" operation in their response. This API is used to register for their service, and should include details about the operation (e.g. a localized name for the resource provider + any special considerations like PII release). + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set name of the API. The name of the operation being performed on this particular object. It should match the action name that appears in RBAC / the event service. Examples of operations include: * Microsoft.Compute/virtualMachine/capture/action * Microsoft.Compute/virtualMachine/restart/action * Microsoft.Compute/virtualMachine/write * Microsoft.Compute/virtualMachine/read * Microsoft.Compute/virtualMachine/delete Each action should include, in order: (1) Resource Provider Namespace (2) Type hierarchy for which the action applies (e.g. server/databases for a SQL Azure database) (3) Read, Write, Action or Delete indicating which type applies. If it is a PUT/PATCH on a collection or named value, Write should be used. If it is a GET, Read should be used. If it is a DELETE, Delete should be used. If it is a POST, Action should be used. As a note: all resource providers would need to include the "{Resource Provider Namespace}/register/action" operation in their response. This API is used to register for their service, and should include details about the operation (e.g. a localized name for the resource provider + any special considerations like PII release). + * + * @param name the name value to set + * @return the OperationsDiscoveryInner object itself. + */ + public OperationsDiscoveryInner withName(String name) { + this.name = name; + return this; + } + + /** + * Get object type. + * + * @return the display value + */ + public Display display() { + return this.display; + } + + /** + * Set object type. + * + * @param display the display value to set + * @return the OperationsDiscoveryInner object itself. + */ + public OperationsDiscoveryInner withDisplay(Display display) { + this.display = display; + return this; + } + + /** + * Get origin. The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default value is "user,system". + * + * @return the origin value + */ + public String origin() { + return this.origin; + } + + /** + * Set origin. The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. Default value is "user,system". + * + * @param origin the origin value to set + * @return the OperationsDiscoveryInner object itself. + */ + public OperationsDiscoveryInner withOrigin(String origin) { + this.origin = origin; + return this; + } + + /** + * Get properties. Reserved for future use. + * + * @return the properties value + */ + public Object properties() { + return this.properties; + } + + /** + * Set properties. Reserved for future use. + * + * @param properties the properties value to set + * @return the OperationsDiscoveryInner object itself. + */ + public OperationsDiscoveryInner withProperties(Object properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsImpl.java new file mode 100644 index 0000000000000..1942f1cfdfc9b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsImpl.java @@ -0,0 +1,68 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * jkl + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Operations; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.PagedList; +import com.microsoft.azure.Page; +import com.microsoft.azure.arm.utils.PagedListConverter; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.OperationsDiscovery; + +class OperationsImpl extends WrapperImpl implements Operations { + private PagedListConverter converter; + private final RecoveryServicesManager manager; + + OperationsImpl(RecoveryServicesManager manager) { + super(manager.inner().operations()); + this.manager = manager; + this.converter = new PagedListConverter() { + @Override + public Observable typeConvertAsync(OperationsDiscoveryInner inner) { + return Observable.just((OperationsDiscovery) wrapModel(inner)); + } + }; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private OperationsDiscoveryImpl wrapModel(OperationsDiscoveryInner inner) { + return new OperationsDiscoveryImpl(inner, manager()); + } + + @Override + public PagedList list() { + OperationsInner client = this.inner(); + return converter.convert(client.listByResourceGroup()); + } + + @Override + public Observable listAsync() { + OperationsInner client = this.inner(); + return client.listByResourceGroupAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public OperationsDiscovery call(OperationsDiscoveryInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsInner.java new file mode 100644 index 0000000000000..3e8a6d39b8a66 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/OperationsInner.java @@ -0,0 +1,300 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Operations. + */ +public class OperationsInner { + /** The Retrofit service to perform REST calls. */ + private OperationsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of OperationsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public OperationsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(OperationsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Operations to be + * used by Retrofit to perform actually REST calls. + */ + interface OperationsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Operations listByResourceGroup" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/operations") + Observable> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Operations listByResourceGroupNext" }) + @GET + Observable> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<OperationsDiscoveryInner> object if successful. + */ + public PagedList listByResourceGroup() { + ServiceResponse> response = listByResourceGroupSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<OperationsDiscoveryInner> object + */ + public Observable> listByResourceGroupAsync() { + return listByResourceGroupWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<OperationsDiscoveryInner> object + */ + public Observable>> listByResourceGroupWithServiceResponseAsync() { + return listByResourceGroupSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<OperationsDiscoveryInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupSinglePageAsync() { + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByResourceGroup(this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<OperationsDiscoveryInner> object if successful. + */ + public PagedList listByResourceGroupNext(final String nextPageLink) { + ServiceResponse> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<OperationsDiscoveryInner> object + */ + public Observable> listByResourceGroupNextAsync(final String nextPageLink) { + return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<OperationsDiscoveryInner> object + */ + public Observable>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Returns the list of available operations. + * Operation to return the list of available operations. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<OperationsDiscoveryInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PageImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PageImpl.java new file mode 100644 index 0000000000000..c8a0578db774b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PageImpl.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.Page; +import java.util.List; + +/** + * An instance of this class defines a page of Azure resources and a link to + * get the next page of resources, if any. + * + * @param type of Azure resource + */ +public class PageImpl implements Page { + /** + * The link to the next page. + */ + @JsonProperty("nextLink") + private String nextPageLink; + + /** + * The list of items. + */ + @JsonProperty("value") + private List items; + + /** + * Gets the link to the next page. + * + * @return the link to the next page. + */ + @Override + public String nextPageLink() { + return this.nextPageLink; + } + + /** + * Gets the list of items. + * + * @return the list of items in {@link List}. + */ + @Override + public List items() { + return items; + } + + /** + * Sets the link to the next page. + * + * @param nextPageLink the link to the next page. + * @return this Page object itself. + */ + public PageImpl setNextPageLink(String nextPageLink) { + this.nextPageLink = nextPageLink; + return this; + } + + /** + * Sets the list of items. + * + * @param items the list of items in {@link List}. + * @return this Page object itself. + */ + public PageImpl setItems(List items) { + this.items = items; + return this; + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PolicyImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PolicyImpl.java new file mode 100644 index 0000000000000..08dd10b9f6d54 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PolicyImpl.java @@ -0,0 +1,138 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Policy; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdatePolicyInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreatePolicyInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.PolicyProperties; +import rx.functions.Func1; + +class PolicyImpl extends CreatableUpdatableImpl implements Policy, Policy.Definition, Policy.Update { + private final RecoveryServicesManager manager; + private String policyName; + private CreatePolicyInputProperties cproperties; + private UpdatePolicyInputProperties uproperties; + + PolicyImpl(String name, RecoveryServicesManager manager) { + super(name, new PolicyInner()); + this.manager = manager; + // Set resource name + this.policyName = name; + // + this.cproperties = new CreatePolicyInputProperties(); + this.uproperties = new UpdatePolicyInputProperties(); + } + + PolicyImpl(PolicyInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.policyName = inner.name(); + // set resource ancestor and positional variables + this.policyName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationPolicies"); + // + this.cproperties = new CreatePolicyInputProperties(); + this.uproperties = new UpdatePolicyInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationPoliciesInner client = this.manager().inner().replicationPolicies(); + return client.createAsync(this.policyName, this.cproperties) + .map(new Func1() { + @Override + public PolicyInner call(PolicyInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationPoliciesInner client = this.manager().inner().replicationPolicies(); + return client.updateAsync(this.policyName, this.uproperties) + .map(new Func1() { + @Override + public PolicyInner call(PolicyInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationPoliciesInner client = this.manager().inner().replicationPolicies(); + return client.getAsync(this.policyName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new CreatePolicyInputProperties(); + this.uproperties = new UpdatePolicyInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public PolicyProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public PolicyImpl withExistingVault() { + return this; + } + + @Override + public PolicyImpl withProperties(CreatePolicyInputProperties properties) { + this.cproperties = properties; + return this; + } + + @Override + public PolicyImpl withProperties(UpdatePolicyInputProperties properties) { + this.uproperties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PolicyInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PolicyInner.java new file mode 100644 index 0000000000000..668c6dc9be053 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/PolicyInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.PolicyProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Protection profile details. + */ +public class PolicyInner extends ProxyResource { + /** + * The custom data. + */ + @JsonProperty(value = "properties") + private PolicyProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the custom data. + * + * @return the properties value + */ + public PolicyProperties properties() { + return this.properties; + } + + /** + * Set the custom data. + * + * @param properties the properties value to set + * @return the PolicyInner object itself. + */ + public PolicyInner withProperties(PolicyProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the PolicyInner object itself. + */ + public PolicyInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectableItemImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectableItemImpl.java new file mode 100644 index 0000000000000..faae0de8a0aec --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectableItemImpl.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectableItem; +import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectableItemProperties; + +class ProtectableItemImpl extends IndexableRefreshableWrapperImpl implements ProtectableItem { + private final RecoveryServicesManager manager; + private String fabricName; + private String protectionContainerName; + private String protectableItemName; + + ProtectableItemImpl(ProtectableItemInner inner, RecoveryServicesManager manager) { + super(null, inner); + this.manager = manager; + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.protectionContainerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainers"); + this.protectableItemName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectableItems"); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + protected Observable getInnerAsync() { + ReplicationProtectableItemsInner client = this.manager().inner().replicationProtectableItems(); + return client.getAsync(this.fabricName, this.protectionContainerName, this.protectableItemName); + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public ProtectableItemProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectableItemInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectableItemInner.java new file mode 100644 index 0000000000000..72bd6ffc91512 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectableItemInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectableItemProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Replication protected item. + */ +public class ProtectableItemInner extends ProxyResource { + /** + * The custom data. + */ + @JsonProperty(value = "properties") + private ProtectableItemProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the custom data. + * + * @return the properties value + */ + public ProtectableItemProperties properties() { + return this.properties; + } + + /** + * Set the custom data. + * + * @param properties the properties value to set + * @return the ProtectableItemInner object itself. + */ + public ProtectableItemInner withProperties(ProtectableItemProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the ProtectableItemInner object itself. + */ + public ProtectableItemInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerImpl.java new file mode 100644 index 0000000000000..f129ea450d7d4 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerImpl.java @@ -0,0 +1,139 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainer; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateProtectionContainerInputProperties; +import java.util.List; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainerProperties; +import rx.functions.Func1; + +class ProtectionContainerImpl extends CreatableUpdatableImpl implements ProtectionContainer, ProtectionContainer.Definition, ProtectionContainer.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private String protectionContainerName; + private CreateProtectionContainerInputProperties cproperties; + private CreateProtectionContainerInputProperties uproperties; + + ProtectionContainerImpl(String name, RecoveryServicesManager manager) { + super(name, new ProtectionContainerInner()); + this.manager = manager; + // Set resource name + this.protectionContainerName = name; + // + this.cproperties = new CreateProtectionContainerInputProperties(); + this.uproperties = new CreateProtectionContainerInputProperties(); + } + + ProtectionContainerImpl(ProtectionContainerInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.protectionContainerName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.protectionContainerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainers"); + // + this.cproperties = new CreateProtectionContainerInputProperties(); + this.uproperties = new CreateProtectionContainerInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationProtectionContainersInner client = this.manager().inner().replicationProtectionContainers(); + return client.createAsync(this.fabricName, this.protectionContainerName, this.cproperties) + .map(new Func1() { + @Override + public ProtectionContainerInner call(ProtectionContainerInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationProtectionContainersInner client = this.manager().inner().replicationProtectionContainers(); + return client.createAsync(this.fabricName, this.protectionContainerName, this.uproperties) + .map(new Func1() { + @Override + public ProtectionContainerInner call(ProtectionContainerInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationProtectionContainersInner client = this.manager().inner().replicationProtectionContainers(); + return client.getAsync(this.fabricName, this.protectionContainerName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new CreateProtectionContainerInputProperties(); + this.uproperties = new CreateProtectionContainerInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public ProtectionContainerProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public ProtectionContainerImpl withExistingReplicationFabric(String fabricName) { + this.fabricName = fabricName; + return this; + } + + @Override + public ProtectionContainerImpl withProperties(CreateProtectionContainerInputProperties properties) { + if (isInCreateMode()) { + this.cproperties = properties; + } else { + this.uproperties = properties; + } + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerInner.java new file mode 100644 index 0000000000000..f5d5a85790b38 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainerProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Protection container details. + */ +public class ProtectionContainerInner extends ProxyResource { + /** + * The custom data. + */ + @JsonProperty(value = "properties") + private ProtectionContainerProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the custom data. + * + * @return the properties value + */ + public ProtectionContainerProperties properties() { + return this.properties; + } + + /** + * Set the custom data. + * + * @param properties the properties value to set + * @return the ProtectionContainerInner object itself. + */ + public ProtectionContainerInner withProperties(ProtectionContainerProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the ProtectionContainerInner object itself. + */ + public ProtectionContainerInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerMappingImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerMappingImpl.java new file mode 100644 index 0000000000000..af475718e55dd --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerMappingImpl.java @@ -0,0 +1,144 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainerMapping; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateProtectionContainerMappingInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateProtectionContainerMappingInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainerMappingProperties; +import rx.functions.Func1; + +class ProtectionContainerMappingImpl extends CreatableUpdatableImpl implements ProtectionContainerMapping, ProtectionContainerMapping.Definition, ProtectionContainerMapping.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private String protectionContainerName; + private String mappingName; + private CreateProtectionContainerMappingInputProperties cproperties; + private UpdateProtectionContainerMappingInputProperties uproperties; + + ProtectionContainerMappingImpl(String name, RecoveryServicesManager manager) { + super(name, new ProtectionContainerMappingInner()); + this.manager = manager; + // Set resource name + this.mappingName = name; + // + this.cproperties = new CreateProtectionContainerMappingInputProperties(); + this.uproperties = new UpdateProtectionContainerMappingInputProperties(); + } + + ProtectionContainerMappingImpl(ProtectionContainerMappingInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.mappingName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.protectionContainerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainers"); + this.mappingName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainerMappings"); + // + this.cproperties = new CreateProtectionContainerMappingInputProperties(); + this.uproperties = new UpdateProtectionContainerMappingInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationProtectionContainerMappingsInner client = this.manager().inner().replicationProtectionContainerMappings(); + return client.createAsync(this.fabricName, this.protectionContainerName, this.mappingName, this.cproperties) + .map(new Func1() { + @Override + public ProtectionContainerMappingInner call(ProtectionContainerMappingInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationProtectionContainerMappingsInner client = this.manager().inner().replicationProtectionContainerMappings(); + return client.updateAsync(this.fabricName, this.protectionContainerName, this.mappingName, this.uproperties) + .map(new Func1() { + @Override + public ProtectionContainerMappingInner call(ProtectionContainerMappingInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationProtectionContainerMappingsInner client = this.manager().inner().replicationProtectionContainerMappings(); + return client.getAsync(this.fabricName, this.protectionContainerName, this.mappingName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new CreateProtectionContainerMappingInputProperties(); + this.uproperties = new UpdateProtectionContainerMappingInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public ProtectionContainerMappingProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public ProtectionContainerMappingImpl withExistingReplicationProtectionContainer(String fabricName, String protectionContainerName) { + this.fabricName = fabricName; + this.protectionContainerName = protectionContainerName; + return this; + } + + @Override + public ProtectionContainerMappingImpl withProperties(CreateProtectionContainerMappingInputProperties properties) { + this.cproperties = properties; + return this; + } + + @Override + public ProtectionContainerMappingImpl withProperties(UpdateProtectionContainerMappingInputProperties properties) { + this.uproperties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerMappingInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerMappingInner.java new file mode 100644 index 0000000000000..81889e4215aac --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ProtectionContainerMappingInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainerMappingProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Protection container mapping object. + */ +public class ProtectionContainerMappingInner extends ProxyResource { + /** + * The custom data. + */ + @JsonProperty(value = "properties") + private ProtectionContainerMappingProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the custom data. + * + * @return the properties value + */ + public ProtectionContainerMappingProperties properties() { + return this.properties; + } + + /** + * Set the custom data. + * + * @param properties the properties value to set + * @return the ProtectionContainerMappingInner object itself. + */ + public ProtectionContainerMappingInner withProperties(ProtectionContainerMappingProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the ProtectionContainerMappingInner object itself. + */ + public ProtectionContainerMappingInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPlanImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPlanImpl.java new file mode 100644 index 0000000000000..1a3994aca4946 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPlanImpl.java @@ -0,0 +1,139 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlan; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateRecoveryPlanInputProperties; +import java.util.List; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateRecoveryPlanInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanProperties; +import rx.functions.Func1; + +class RecoveryPlanImpl extends CreatableUpdatableImpl implements RecoveryPlan, RecoveryPlan.Definition, RecoveryPlan.Update { + private final RecoveryServicesManager manager; + private String recoveryPlanName; + private CreateRecoveryPlanInputProperties cproperties; + private UpdateRecoveryPlanInputProperties uproperties; + + RecoveryPlanImpl(String name, RecoveryServicesManager manager) { + super(name, new RecoveryPlanInner()); + this.manager = manager; + // Set resource name + this.recoveryPlanName = name; + // + this.cproperties = new CreateRecoveryPlanInputProperties(); + this.uproperties = new UpdateRecoveryPlanInputProperties(); + } + + RecoveryPlanImpl(RecoveryPlanInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.recoveryPlanName = inner.name(); + // set resource ancestor and positional variables + this.recoveryPlanName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationRecoveryPlans"); + // + this.cproperties = new CreateRecoveryPlanInputProperties(); + this.uproperties = new UpdateRecoveryPlanInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationRecoveryPlansInner client = this.manager().inner().replicationRecoveryPlans(); + return client.createAsync(this.recoveryPlanName, this.cproperties) + .map(new Func1() { + @Override + public RecoveryPlanInner call(RecoveryPlanInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationRecoveryPlansInner client = this.manager().inner().replicationRecoveryPlans(); + return client.updateAsync(this.recoveryPlanName, this.uproperties) + .map(new Func1() { + @Override + public RecoveryPlanInner call(RecoveryPlanInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationRecoveryPlansInner client = this.manager().inner().replicationRecoveryPlans(); + return client.getAsync(this.recoveryPlanName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new CreateRecoveryPlanInputProperties(); + this.uproperties = new UpdateRecoveryPlanInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public RecoveryPlanProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public RecoveryPlanImpl withExistingVault() { + return this; + } + + @Override + public RecoveryPlanImpl withProperties(CreateRecoveryPlanInputProperties properties) { + this.cproperties = properties; + return this; + } + + @Override + public RecoveryPlanImpl withProperties(UpdateRecoveryPlanInputProperties properties) { + this.uproperties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPlanInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPlanInner.java new file mode 100644 index 0000000000000..0b92b6419cdfc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPlanInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Recovery plan details. + */ +public class RecoveryPlanInner extends ProxyResource { + /** + * The custom details. + */ + @JsonProperty(value = "properties") + private RecoveryPlanProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the custom details. + * + * @return the properties value + */ + public RecoveryPlanProperties properties() { + return this.properties; + } + + /** + * Set the custom details. + * + * @param properties the properties value to set + * @return the RecoveryPlanInner object itself. + */ + public RecoveryPlanInner withProperties(RecoveryPlanProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the RecoveryPlanInner object itself. + */ + public RecoveryPlanInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointImpl.java new file mode 100644 index 0000000000000..523b1d1122d1b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointImpl.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPoint; +import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPointProperties; + +class RecoveryPointImpl extends IndexableRefreshableWrapperImpl implements RecoveryPoint { + private final RecoveryServicesManager manager; + private String fabricName; + private String protectionContainerName; + private String replicatedProtectedItemName; + private String recoveryPointName; + + RecoveryPointImpl(RecoveryPointInner inner, RecoveryServicesManager manager) { + super(null, inner); + this.manager = manager; + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.protectionContainerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainers"); + this.replicatedProtectedItemName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectedItems"); + this.recoveryPointName = IdParsingUtils.getValueFromIdByName(inner.id(), "recoveryPoints"); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + protected Observable getInnerAsync() { + RecoveryPointsInner client = this.manager().inner().recoveryPoints(); + return client.getAsync(this.fabricName, this.protectionContainerName, this.replicatedProtectedItemName, this.recoveryPointName); + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public RecoveryPointProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointInner.java new file mode 100644 index 0000000000000..223908daf8121 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPointProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Base class representing a recovery point. + */ +public class RecoveryPointInner extends ProxyResource { + /** + * Recovery point related data. + */ + @JsonProperty(value = "properties") + private RecoveryPointProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get recovery point related data. + * + * @return the properties value + */ + public RecoveryPointProperties properties() { + return this.properties; + } + + /** + * Set recovery point related data. + * + * @param properties the properties value to set + * @return the RecoveryPointInner object itself. + */ + public RecoveryPointInner withProperties(RecoveryPointProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the RecoveryPointInner object itself. + */ + public RecoveryPointInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointsImpl.java new file mode 100644 index 0000000000000..8b4a8fc8a660c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointsImpl.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPoints; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPoint; + +class RecoveryPointsImpl extends WrapperImpl implements RecoveryPoints { + private final RecoveryServicesManager manager; + + RecoveryPointsImpl(RecoveryServicesManager manager) { + super(manager.inner().recoveryPoints()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private RecoveryPointImpl wrapModel(RecoveryPointInner inner) { + return new RecoveryPointImpl(inner, manager()); + } + + @Override + public Observable listByReplicationProtectedItemsAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + RecoveryPointsInner client = this.inner(); + return client.listByReplicationProtectedItemsAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public RecoveryPoint call(RecoveryPointInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, String recoveryPointName) { + RecoveryPointsInner client = this.inner(); + return client.getAsync(fabricName, protectionContainerName, replicatedProtectedItemName, recoveryPointName) + .map(new Func1() { + @Override + public RecoveryPoint call(RecoveryPointInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointsInner.java new file mode 100644 index 0000000000000..b8d951cf0a49c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryPointsInner.java @@ -0,0 +1,442 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in RecoveryPoints. + */ +public class RecoveryPointsInner { + /** The Retrofit service to perform REST calls. */ + private RecoveryPointsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of RecoveryPointsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public RecoveryPointsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(RecoveryPointsService.class); + this.client = client; + } + + /** + * The interface defining all the services for RecoveryPoints to be + * used by Retrofit to perform actually REST calls. + */ + interface RecoveryPointsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPoints listByReplicationProtectedItems" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/recoveryPoints") + Observable> listByReplicationProtectedItems(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPoints get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/recoveryPoints/{recoveryPointName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Path("recoveryPointName") String recoveryPointName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPoints listByReplicationProtectedItemsNext" }) + @GET + Observable> listByReplicationProtectedItemsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<RecoveryPointInner> object if successful. + */ + public PagedList listByReplicationProtectedItems(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + ServiceResponse> response = listByReplicationProtectedItemsSinglePageAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectedItemsAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectedItemsSinglePageAsync(fabricName, protectionContainerName, replicatedProtectedItemName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryPointInner> object + */ + public Observable> listByReplicationProtectedItemsAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + return listByReplicationProtectedItemsWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryPointInner> object + */ + public Observable>> listByReplicationProtectedItemsWithServiceResponseAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + return listByReplicationProtectedItemsSinglePageAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectedItemsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + ServiceResponse> * @param fabricName The fabric name. + ServiceResponse> * @param protectionContainerName The protection container name. + ServiceResponse> * @param replicatedProtectedItemName The replication protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RecoveryPointInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectedItemsSinglePageAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationProtectedItems(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectedItemsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectedItemsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Get a recovery point. + * Get the details of specified recovery point. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @param recoveryPointName The recovery point name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPointInner object if successful. + */ + public RecoveryPointInner get(String fabricName, String protectionContainerName, String replicatedProtectedItemName, String recoveryPointName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, recoveryPointName).toBlocking().single().body(); + } + + /** + * Get a recovery point. + * Get the details of specified recovery point. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @param recoveryPointName The recovery point name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, String recoveryPointName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, recoveryPointName), serviceCallback); + } + + /** + * Get a recovery point. + * Get the details of specified recovery point. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @param recoveryPointName The recovery point name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPointInner object + */ + public Observable getAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, String recoveryPointName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, recoveryPointName).map(new Func1, RecoveryPointInner>() { + @Override + public RecoveryPointInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Get a recovery point. + * Get the details of specified recovery point. + * + * @param fabricName The fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replication protected item's name. + * @param recoveryPointName The recovery point name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPointInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, String recoveryPointName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (recoveryPointName == null) { + throw new IllegalArgumentException("Parameter recoveryPointName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, recoveryPointName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<RecoveryPointInner> object if successful. + */ + public PagedList listByReplicationProtectedItemsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectedItemsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryPointInner> object + */ + public Observable> listByReplicationProtectedItemsNextAsync(final String nextPageLink) { + return listByReplicationProtectedItemsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryPointInner> object + */ + public Observable>> listByReplicationProtectedItemsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectedItemsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Get recovery points for a replication protected item. + * Lists the available recovery points for a replication protected item. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RecoveryPointInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectedItemsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationProtectedItemsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectedItemsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectedItemsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesManager.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesManager.java new file mode 100644 index 0000000000000..c3c43fa6f1952 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesManager.java @@ -0,0 +1,363 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.AzureResponseBuilder; +import com.microsoft.azure.credentials.AzureTokenCredentials; +import com.microsoft.azure.management.apigeneration.Beta; +import com.microsoft.azure.management.apigeneration.Beta.SinceVersion; +import com.microsoft.azure.arm.resources.AzureConfigurable; +import com.microsoft.azure.serializer.AzureJacksonAdapter; +import com.microsoft.rest.RestClient; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Operations; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationAlertSettings; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationEvents; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationLogicalNetworks; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworks; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationRecoveryPoints; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectableItems; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPoints; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TargetComputeSizes; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassifications; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationVaultHealths; +import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl; +import com.microsoft.azure.arm.resources.implementation.ManagerCore; + +/** + * Entry point to Azure RecoveryServices resource management. + */ +public final class RecoveryServicesManager extends ManagerCore { + private Operations operations; + private ReplicationAlertSettings replicationAlertSettings; + private ReplicationEvents replicationEvents; + private ReplicationFabrics replicationFabrics; + private ReplicationLogicalNetworks replicationLogicalNetworks; + private ReplicationNetworks replicationNetworks; + private ReplicationNetworkMappings replicationNetworkMappings; + private ReplicationProtectionContainers replicationProtectionContainers; + private ReplicationMigrationItems replicationMigrationItems; + private MigrationRecoveryPoints migrationRecoveryPoints; + private ReplicationProtectableItems replicationProtectableItems; + private ReplicationProtectedItems replicationProtectedItems; + private RecoveryPoints recoveryPoints; + private TargetComputeSizes targetComputeSizes; + private ReplicationProtectionContainerMappings replicationProtectionContainerMappings; + private ReplicationRecoveryServicesProviders replicationRecoveryServicesProviders; + private ReplicationStorageClassifications replicationStorageClassifications; + private ReplicationStorageClassificationMappings replicationStorageClassificationMappings; + private ReplicationvCenters replicationvCenters; + private ReplicationJobs replicationJobs; + private ReplicationPolicies replicationPolicies; + private ReplicationRecoveryPlans replicationRecoveryPlans; + private ReplicationVaultHealths replicationVaultHealths; + /** + * Get a Configurable instance that can be used to create RecoveryServicesManager with optional configuration. + * + * @return the instance allowing configurations + */ + public static Configurable configure() { + return new RecoveryServicesManager.ConfigurableImpl(); + } + /** + * Creates an instance of RecoveryServicesManager that exposes RecoveryServices resource management API entry points. + * + * @param credentials the credentials to use + * @param subscriptionId the subscription UUID + * @return the RecoveryServicesManager + */ + public static RecoveryServicesManager authenticate(AzureTokenCredentials credentials, String subscriptionId) { + return new RecoveryServicesManager(new RestClient.Builder() + .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) + .withCredentials(credentials) + .withSerializerAdapter(new AzureJacksonAdapter()) + .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) + .build(), subscriptionId); + } + /** + * Creates an instance of RecoveryServicesManager that exposes RecoveryServices resource management API entry points. + * + * @param restClient the RestClient to be used for API calls. + * @param subscriptionId the subscription UUID + * @return the RecoveryServicesManager + */ + public static RecoveryServicesManager authenticate(RestClient restClient, String subscriptionId) { + return new RecoveryServicesManager(restClient, subscriptionId); + } + /** + * The interface allowing configurations to be set. + */ + public interface Configurable extends AzureConfigurable { + /** + * Creates an instance of RecoveryServicesManager that exposes RecoveryServices management API entry points. + * + * @param credentials the credentials to use + * @param subscriptionId the subscription UUID + * @return the interface exposing RecoveryServices management API entry points that work across subscriptions + */ + RecoveryServicesManager authenticate(AzureTokenCredentials credentials, String subscriptionId); + } + + /** + * @return Entry point to manage Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(this); + } + return this.operations; + } + + /** + * @return Entry point to manage ReplicationAlertSettings. + */ + public ReplicationAlertSettings replicationAlertSettings() { + if (this.replicationAlertSettings == null) { + this.replicationAlertSettings = new ReplicationAlertSettingsImpl(this); + } + return this.replicationAlertSettings; + } + + /** + * @return Entry point to manage ReplicationEvents. + */ + public ReplicationEvents replicationEvents() { + if (this.replicationEvents == null) { + this.replicationEvents = new ReplicationEventsImpl(this); + } + return this.replicationEvents; + } + + /** + * @return Entry point to manage ReplicationFabrics. + */ + public ReplicationFabrics replicationFabrics() { + if (this.replicationFabrics == null) { + this.replicationFabrics = new ReplicationFabricsImpl(this); + } + return this.replicationFabrics; + } + + /** + * @return Entry point to manage ReplicationLogicalNetworks. + */ + public ReplicationLogicalNetworks replicationLogicalNetworks() { + if (this.replicationLogicalNetworks == null) { + this.replicationLogicalNetworks = new ReplicationLogicalNetworksImpl(this); + } + return this.replicationLogicalNetworks; + } + + /** + * @return Entry point to manage ReplicationNetworks. + */ + public ReplicationNetworks replicationNetworks() { + if (this.replicationNetworks == null) { + this.replicationNetworks = new ReplicationNetworksImpl(this); + } + return this.replicationNetworks; + } + + /** + * @return Entry point to manage ReplicationNetworkMappings. + */ + public ReplicationNetworkMappings replicationNetworkMappings() { + if (this.replicationNetworkMappings == null) { + this.replicationNetworkMappings = new ReplicationNetworkMappingsImpl(this); + } + return this.replicationNetworkMappings; + } + + /** + * @return Entry point to manage ReplicationProtectionContainers. + */ + public ReplicationProtectionContainers replicationProtectionContainers() { + if (this.replicationProtectionContainers == null) { + this.replicationProtectionContainers = new ReplicationProtectionContainersImpl(this); + } + return this.replicationProtectionContainers; + } + + /** + * @return Entry point to manage ReplicationMigrationItems. + */ + public ReplicationMigrationItems replicationMigrationItems() { + if (this.replicationMigrationItems == null) { + this.replicationMigrationItems = new ReplicationMigrationItemsImpl(this); + } + return this.replicationMigrationItems; + } + + /** + * @return Entry point to manage MigrationRecoveryPoints. + */ + public MigrationRecoveryPoints migrationRecoveryPoints() { + if (this.migrationRecoveryPoints == null) { + this.migrationRecoveryPoints = new MigrationRecoveryPointsImpl(this); + } + return this.migrationRecoveryPoints; + } + + /** + * @return Entry point to manage ReplicationProtectableItems. + */ + public ReplicationProtectableItems replicationProtectableItems() { + if (this.replicationProtectableItems == null) { + this.replicationProtectableItems = new ReplicationProtectableItemsImpl(this); + } + return this.replicationProtectableItems; + } + + /** + * @return Entry point to manage ReplicationProtectedItems. + */ + public ReplicationProtectedItems replicationProtectedItems() { + if (this.replicationProtectedItems == null) { + this.replicationProtectedItems = new ReplicationProtectedItemsImpl(this); + } + return this.replicationProtectedItems; + } + + /** + * @return Entry point to manage RecoveryPoints. + */ + public RecoveryPoints recoveryPoints() { + if (this.recoveryPoints == null) { + this.recoveryPoints = new RecoveryPointsImpl(this); + } + return this.recoveryPoints; + } + + /** + * @return Entry point to manage TargetComputeSizes. + */ + public TargetComputeSizes targetComputeSizes() { + if (this.targetComputeSizes == null) { + this.targetComputeSizes = new TargetComputeSizesImpl(this); + } + return this.targetComputeSizes; + } + + /** + * @return Entry point to manage ReplicationProtectionContainerMappings. + */ + public ReplicationProtectionContainerMappings replicationProtectionContainerMappings() { + if (this.replicationProtectionContainerMappings == null) { + this.replicationProtectionContainerMappings = new ReplicationProtectionContainerMappingsImpl(this); + } + return this.replicationProtectionContainerMappings; + } + + /** + * @return Entry point to manage ReplicationRecoveryServicesProviders. + */ + public ReplicationRecoveryServicesProviders replicationRecoveryServicesProviders() { + if (this.replicationRecoveryServicesProviders == null) { + this.replicationRecoveryServicesProviders = new ReplicationRecoveryServicesProvidersImpl(this); + } + return this.replicationRecoveryServicesProviders; + } + + /** + * @return Entry point to manage ReplicationStorageClassifications. + */ + public ReplicationStorageClassifications replicationStorageClassifications() { + if (this.replicationStorageClassifications == null) { + this.replicationStorageClassifications = new ReplicationStorageClassificationsImpl(this); + } + return this.replicationStorageClassifications; + } + + /** + * @return Entry point to manage ReplicationStorageClassificationMappings. + */ + public ReplicationStorageClassificationMappings replicationStorageClassificationMappings() { + if (this.replicationStorageClassificationMappings == null) { + this.replicationStorageClassificationMappings = new ReplicationStorageClassificationMappingsImpl(this); + } + return this.replicationStorageClassificationMappings; + } + + /** + * @return Entry point to manage ReplicationvCenters. + */ + public ReplicationvCenters replicationvCenters() { + if (this.replicationvCenters == null) { + this.replicationvCenters = new ReplicationvCentersImpl(this); + } + return this.replicationvCenters; + } + + /** + * @return Entry point to manage ReplicationJobs. + */ + public ReplicationJobs replicationJobs() { + if (this.replicationJobs == null) { + this.replicationJobs = new ReplicationJobsImpl(this); + } + return this.replicationJobs; + } + + /** + * @return Entry point to manage ReplicationPolicies. + */ + public ReplicationPolicies replicationPolicies() { + if (this.replicationPolicies == null) { + this.replicationPolicies = new ReplicationPoliciesImpl(this); + } + return this.replicationPolicies; + } + + /** + * @return Entry point to manage ReplicationRecoveryPlans. + */ + public ReplicationRecoveryPlans replicationRecoveryPlans() { + if (this.replicationRecoveryPlans == null) { + this.replicationRecoveryPlans = new ReplicationRecoveryPlansImpl(this); + } + return this.replicationRecoveryPlans; + } + + /** + * @return Entry point to manage ReplicationVaultHealths. + */ + public ReplicationVaultHealths replicationVaultHealths() { + if (this.replicationVaultHealths == null) { + this.replicationVaultHealths = new ReplicationVaultHealthsImpl(this); + } + return this.replicationVaultHealths; + } + + /** + * The implementation for Configurable interface. + */ + private static final class ConfigurableImpl extends AzureConfigurableCoreImpl implements Configurable { + public RecoveryServicesManager authenticate(AzureTokenCredentials credentials, String subscriptionId) { + return RecoveryServicesManager.authenticate(buildRestClient(credentials), subscriptionId); + } + } + private RecoveryServicesManager(RestClient restClient, String subscriptionId) { + super( + restClient, + subscriptionId, + new SiteRecoveryManagementClientImpl(restClient).withSubscriptionId(subscriptionId)); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesProviderImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesProviderImpl.java new file mode 100644 index 0000000000000..1982a185bdf7b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesProviderImpl.java @@ -0,0 +1,138 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryServicesProvider; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.AddRecoveryServicesProviderInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryServicesProviderProperties; +import rx.functions.Func1; + +class RecoveryServicesProviderImpl extends CreatableUpdatableImpl implements RecoveryServicesProvider, RecoveryServicesProvider.Definition, RecoveryServicesProvider.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private String providerName; + private AddRecoveryServicesProviderInputProperties cproperties; + private AddRecoveryServicesProviderInputProperties uproperties; + + RecoveryServicesProviderImpl(String name, RecoveryServicesManager manager) { + super(name, new RecoveryServicesProviderInner()); + this.manager = manager; + // Set resource name + this.providerName = name; + // + this.cproperties = new AddRecoveryServicesProviderInputProperties(); + this.uproperties = new AddRecoveryServicesProviderInputProperties(); + } + + RecoveryServicesProviderImpl(RecoveryServicesProviderInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.providerName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.providerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationRecoveryServicesProviders"); + // + this.cproperties = new AddRecoveryServicesProviderInputProperties(); + this.uproperties = new AddRecoveryServicesProviderInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationRecoveryServicesProvidersInner client = this.manager().inner().replicationRecoveryServicesProviders(); + return client.createAsync(this.fabricName, this.providerName, this.cproperties) + .map(new Func1() { + @Override + public RecoveryServicesProviderInner call(RecoveryServicesProviderInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationRecoveryServicesProvidersInner client = this.manager().inner().replicationRecoveryServicesProviders(); + return client.createAsync(this.fabricName, this.providerName, this.uproperties) + .map(new Func1() { + @Override + public RecoveryServicesProviderInner call(RecoveryServicesProviderInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationRecoveryServicesProvidersInner client = this.manager().inner().replicationRecoveryServicesProviders(); + return client.getAsync(this.fabricName, this.providerName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new AddRecoveryServicesProviderInputProperties(); + this.uproperties = new AddRecoveryServicesProviderInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public RecoveryServicesProviderProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public RecoveryServicesProviderImpl withExistingReplicationFabric(String fabricName) { + this.fabricName = fabricName; + return this; + } + + @Override + public RecoveryServicesProviderImpl withProperties(AddRecoveryServicesProviderInputProperties properties) { + if (isInCreateMode()) { + this.cproperties = properties; + } else { + this.uproperties = properties; + } + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesProviderInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesProviderInner.java new file mode 100644 index 0000000000000..7936ad21ce4a5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/RecoveryServicesProviderInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryServicesProviderProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Provider details. + */ +public class RecoveryServicesProviderInner extends ProxyResource { + /** + * Provider properties. + */ + @JsonProperty(value = "properties") + private RecoveryServicesProviderProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get provider properties. + * + * @return the properties value + */ + public RecoveryServicesProviderProperties properties() { + return this.properties; + } + + /** + * Set provider properties. + * + * @param properties the properties value to set + * @return the RecoveryServicesProviderInner object itself. + */ + public RecoveryServicesProviderInner withProperties(RecoveryServicesProviderProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the RecoveryServicesProviderInner object itself. + */ + public RecoveryServicesProviderInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationAlertSettingsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationAlertSettingsImpl.java new file mode 100644 index 0000000000000..48820c65d3f7c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationAlertSettingsImpl.java @@ -0,0 +1,74 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationAlertSettings; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Alert; + +class ReplicationAlertSettingsImpl extends WrapperImpl implements ReplicationAlertSettings { + private final RecoveryServicesManager manager; + + ReplicationAlertSettingsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationAlertSettings()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public AlertImpl define(String name) { + return wrapModel(name); + } + + private AlertImpl wrapModel(AlertInner inner) { + return new AlertImpl(inner, manager()); + } + + private AlertImpl wrapModel(String name) { + return new AlertImpl(name, this.manager()); + } + + @Override + public Observable listAsync() { + ReplicationAlertSettingsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Alert call(AlertInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String alertSettingName) { + ReplicationAlertSettingsInner client = this.inner(); + return client.getAsync(alertSettingName) + .map(new Func1() { + @Override + public Alert call(AlertInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationAlertSettingsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationAlertSettingsInner.java new file mode 100644 index 0000000000000..b143d88c076be --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationAlertSettingsInner.java @@ -0,0 +1,587 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ConfigureAlertRequest; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ConfigureAlertRequestProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationAlertSettings. + */ +public class ReplicationAlertSettingsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationAlertSettingsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationAlertSettingsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationAlertSettingsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationAlertSettingsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationAlertSettings to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationAlertSettingsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationAlertSettings list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationAlertSettings") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationAlertSettings get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationAlertSettings/{alertSettingName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("alertSettingName") String alertSettingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationAlertSettings create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationAlertSettings/{alertSettingName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("alertSettingName") String alertSettingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ConfigureAlertRequest request, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationAlertSettings listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<AlertInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AlertInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AlertInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<AlertInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets an email notification(alert) configuration. + * Gets the details of the specified email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification configuration. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the AlertInner object if successful. + */ + public AlertInner get(String alertSettingName) { + return getWithServiceResponseAsync(alertSettingName).toBlocking().single().body(); + } + + /** + * Gets an email notification(alert) configuration. + * Gets the details of the specified email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification configuration. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String alertSettingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(alertSettingName), serviceCallback); + } + + /** + * Gets an email notification(alert) configuration. + * Gets the details of the specified email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification configuration. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AlertInner object + */ + public Observable getAsync(String alertSettingName) { + return getWithServiceResponseAsync(alertSettingName).map(new Func1, AlertInner>() { + @Override + public AlertInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets an email notification(alert) configuration. + * Gets the details of the specified email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification configuration. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AlertInner object + */ + public Observable> getWithServiceResponseAsync(String alertSettingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (alertSettingName == null) { + throw new IllegalArgumentException("Parameter alertSettingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), alertSettingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Configures email notifications for this vault. + * Create or update an email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification(alert) configuration. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the AlertInner object if successful. + */ + public AlertInner create(String alertSettingName) { + return createWithServiceResponseAsync(alertSettingName).toBlocking().single().body(); + } + + /** + * Configures email notifications for this vault. + * Create or update an email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification(alert) configuration. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String alertSettingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(alertSettingName), serviceCallback); + } + + /** + * Configures email notifications for this vault. + * Create or update an email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification(alert) configuration. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AlertInner object + */ + public Observable createAsync(String alertSettingName) { + return createWithServiceResponseAsync(alertSettingName).map(new Func1, AlertInner>() { + @Override + public AlertInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Configures email notifications for this vault. + * Create or update an email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification(alert) configuration. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AlertInner object + */ + public Observable> createWithServiceResponseAsync(String alertSettingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (alertSettingName == null) { + throw new IllegalArgumentException("Parameter alertSettingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final ConfigureAlertRequestProperties properties = null; + ConfigureAlertRequest request = new ConfigureAlertRequest(); + request.withProperties(null); + return service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), alertSettingName, this.client.apiVersion(), this.client.acceptLanguage(), request, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Configures email notifications for this vault. + * Create or update an email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification(alert) configuration. + * @param properties The properties of a configure alert request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the AlertInner object if successful. + */ + public AlertInner create(String alertSettingName, ConfigureAlertRequestProperties properties) { + return createWithServiceResponseAsync(alertSettingName, properties).toBlocking().single().body(); + } + + /** + * Configures email notifications for this vault. + * Create or update an email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification(alert) configuration. + * @param properties The properties of a configure alert request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String alertSettingName, ConfigureAlertRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(alertSettingName, properties), serviceCallback); + } + + /** + * Configures email notifications for this vault. + * Create or update an email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification(alert) configuration. + * @param properties The properties of a configure alert request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AlertInner object + */ + public Observable createAsync(String alertSettingName, ConfigureAlertRequestProperties properties) { + return createWithServiceResponseAsync(alertSettingName, properties).map(new Func1, AlertInner>() { + @Override + public AlertInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Configures email notifications for this vault. + * Create or update an email notification(alert) configuration. + * + * @param alertSettingName The name of the email notification(alert) configuration. + * @param properties The properties of a configure alert request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the AlertInner object + */ + public Observable> createWithServiceResponseAsync(String alertSettingName, ConfigureAlertRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (alertSettingName == null) { + throw new IllegalArgumentException("Parameter alertSettingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + ConfigureAlertRequest request = new ConfigureAlertRequest(); + request.withProperties(properties); + return service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), alertSettingName, this.client.apiVersion(), this.client.acceptLanguage(), request, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse createDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<AlertInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AlertInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AlertInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of configured email notification(alert) configurations. + * Gets the list of email notification(alert) configurations for the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<AlertInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationEventsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationEventsImpl.java new file mode 100644 index 0000000000000..a1f322c6eb6bf --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationEventsImpl.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationEvents; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Event; + +class ReplicationEventsImpl extends WrapperImpl implements ReplicationEvents { + private final RecoveryServicesManager manager; + + ReplicationEventsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationEvents()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private EventImpl wrapModel(EventInner inner) { + return new EventImpl(inner, manager()); + } + + @Override + public Observable listAsync() { + ReplicationEventsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Event call(EventInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String eventName) { + ReplicationEventsInner client = this.inner(); + return client.getAsync(eventName) + .map(new Func1() { + @Override + public Event call(EventInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationEventsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationEventsInner.java new file mode 100644 index 0000000000000..a37b4af36ddd1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationEventsInner.java @@ -0,0 +1,514 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationEvents. + */ +public class ReplicationEventsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationEventsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationEventsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationEventsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationEventsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationEvents to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationEventsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationEvents list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationEvents") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Query("$filter") String filter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationEvents get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationEvents/{eventName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("eventName") String eventName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationEvents listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<EventInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<EventInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<EventInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<EventInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String filter = null; + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<EventInner> object if successful. + */ + public PagedList list(final String filter) { + ServiceResponse> response = listSinglePageAsync(filter).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param filter OData filter options. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final String filter, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(filter), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<EventInner> object + */ + public Observable> listAsync(final String filter) { + return listWithServiceResponseAsync(filter) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<EventInner> object + */ + public Observable>> listWithServiceResponseAsync(final String filter) { + return listSinglePageAsync(filter) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + ServiceResponse> * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<EventInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String filter) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Get the details of an Azure Site recovery event. + * The operation to get the details of an Azure Site recovery event. + * + * @param eventName The name of the Azure Site Recovery event. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the EventInner object if successful. + */ + public EventInner get(String eventName) { + return getWithServiceResponseAsync(eventName).toBlocking().single().body(); + } + + /** + * Get the details of an Azure Site recovery event. + * The operation to get the details of an Azure Site recovery event. + * + * @param eventName The name of the Azure Site Recovery event. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String eventName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(eventName), serviceCallback); + } + + /** + * Get the details of an Azure Site recovery event. + * The operation to get the details of an Azure Site recovery event. + * + * @param eventName The name of the Azure Site Recovery event. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the EventInner object + */ + public Observable getAsync(String eventName) { + return getWithServiceResponseAsync(eventName).map(new Func1, EventInner>() { + @Override + public EventInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Get the details of an Azure Site recovery event. + * The operation to get the details of an Azure Site recovery event. + * + * @param eventName The name of the Azure Site Recovery event. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the EventInner object + */ + public Observable> getWithServiceResponseAsync(String eventName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (eventName == null) { + throw new IllegalArgumentException("Parameter eventName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), eventName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<EventInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<EventInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<EventInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of Azure Site Recovery events. + * Gets the list of Azure Site Recovery events for the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<EventInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationFabricsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationFabricsImpl.java new file mode 100644 index 0000000000000..7afa9e4f412aa --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationFabricsImpl.java @@ -0,0 +1,129 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Fabric; + +class ReplicationFabricsImpl extends WrapperImpl implements ReplicationFabrics { + private final RecoveryServicesManager manager; + + ReplicationFabricsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationFabrics()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public FabricImpl define(String name) { + return wrapModel(name); + } + + private FabricImpl wrapModel(FabricInner inner) { + return new FabricImpl(inner, manager()); + } + + private FabricImpl wrapModel(String name) { + return new FabricImpl(name, this.manager()); + } + + @Override + public Observable checkConsistencyAsync(String fabricName) { + ReplicationFabricsInner client = this.inner(); + return client.checkConsistencyAsync(fabricName) + .map(new Func1() { + @Override + public Fabric call(FabricInner inner) { + return new FabricImpl(inner, manager()); + } + }); + } + + @Override + public Completable migrateToAadAsync(String fabricName) { + ReplicationFabricsInner client = this.inner(); + return client.migrateToAadAsync(fabricName).toCompletable(); + } + + @Override + public Observable reassociateGatewayAsync(String fabricName) { + ReplicationFabricsInner client = this.inner(); + return client.reassociateGatewayAsync(fabricName) + .map(new Func1() { + @Override + public Fabric call(FabricInner inner) { + return new FabricImpl(inner, manager()); + } + }); + } + + @Override + public Completable deleteAsync(String fabricName) { + ReplicationFabricsInner client = this.inner(); + return client.deleteAsync(fabricName).toCompletable(); + } + + @Override + public Observable renewCertificateAsync(String fabricName) { + ReplicationFabricsInner client = this.inner(); + return client.renewCertificateAsync(fabricName) + .map(new Func1() { + @Override + public Fabric call(FabricInner inner) { + return new FabricImpl(inner, manager()); + } + }); + } + + @Override + public Observable listAsync() { + ReplicationFabricsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Fabric call(FabricInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName) { + ReplicationFabricsInner client = this.inner(); + return client.getAsync(fabricName) + .map(new Func1() { + @Override + public Fabric call(FabricInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable purgeAsync(String fabricName) { + ReplicationFabricsInner client = this.inner(); + return client.purgeAsync(fabricName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationFabricsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationFabricsInner.java new file mode 100644 index 0000000000000..2f6782ff082f4 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationFabricsInner.java @@ -0,0 +1,2111 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.FabricCreationInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.FabricCreationInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.FailoverProcessServerRequest; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.FailoverProcessServerRequestProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RenewCertificateInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RenewCertificateInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationFabrics. + */ +public class ReplicationFabricsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationFabricsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationFabricsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationFabricsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationFabricsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationFabrics to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationFabricsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body FabricCreationInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body FabricCreationInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics purge" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}", method = "DELETE", hasBody = true) + Observable> purge(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics beginPurge" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}", method = "DELETE", hasBody = true) + Observable> beginPurge(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics checkConsistency" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/checkConsistency") + Observable> checkConsistency(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics beginCheckConsistency" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/checkConsistency") + Observable> beginCheckConsistency(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics migrateToAad" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/migratetoaad") + Observable> migrateToAad(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics beginMigrateToAad" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/migratetoaad") + Observable> beginMigrateToAad(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics reassociateGateway" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/reassociateGateway") + Observable> reassociateGateway(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body FailoverProcessServerRequest failoverProcessServerRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics beginReassociateGateway" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/reassociateGateway") + Observable> beginReassociateGateway(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body FailoverProcessServerRequest failoverProcessServerRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics delete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/remove") + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics beginDelete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/remove") + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics renewCertificate" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/renewCertificate") + Observable> renewCertificate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RenewCertificateInput renewCertificate, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics beginRenewCertificate" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/renewCertificate") + Observable> beginRenewCertificate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RenewCertificateInput renewCertificate, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationFabrics listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<FabricInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<FabricInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<FabricInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<FabricInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the details of an ASR fabric. + * Gets the details of an Azure Site Recovery fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner get(String fabricName) { + return getWithServiceResponseAsync(fabricName).toBlocking().single().body(); + } + + /** + * Gets the details of an ASR fabric. + * Gets the details of an Azure Site Recovery fabric. + * + * @param fabricName Fabric name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Gets the details of an ASR fabric. + * Gets the details of an Azure Site Recovery fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable getAsync(String fabricName) { + return getWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the details of an ASR fabric. + * Gets the details of an Azure Site Recovery fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner create(String fabricName) { + return createWithServiceResponseAsync(fabricName).toBlocking().last().body(); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName) { + return createWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final FabricCreationInputProperties properties = null; + FabricCreationInput input = new FabricCreationInput(); + input.withProperties(null); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param properties Fabric creation input. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner create(String fabricName, FabricCreationInputProperties properties) { + return createWithServiceResponseAsync(fabricName, properties).toBlocking().last().body(); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param properties Fabric creation input. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, FabricCreationInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, properties), serviceCallback); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param properties Fabric creation input. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, FabricCreationInputProperties properties) { + return createWithServiceResponseAsync(fabricName, properties).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param properties Fabric creation input. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, FabricCreationInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + FabricCreationInput input = new FabricCreationInput(); + input.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner beginCreate(String fabricName) { + return beginCreateWithServiceResponseAsync(fabricName).toBlocking().single().body(); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable beginCreateAsync(String fabricName) { + return beginCreateWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final FabricCreationInputProperties properties = null; + FabricCreationInput input = new FabricCreationInput(); + input.withProperties(null); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param properties Fabric creation input. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner beginCreate(String fabricName, FabricCreationInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, properties).toBlocking().single().body(); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param properties Fabric creation input. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, FabricCreationInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, properties), serviceCallback); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param properties Fabric creation input. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable beginCreateAsync(String fabricName, FabricCreationInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, properties).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates an Azure Site Recovery fabric. + * The operation to create an Azure Site Recovery fabric (for e.g. Hyper-V site). + * + * @param fabricName Name of the ASR fabric. + * @param properties Fabric creation input. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, FabricCreationInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + FabricCreationInput input = new FabricCreationInput(); + input.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void purge(String fabricName) { + purgeWithServiceResponseAsync(fabricName).toBlocking().last().body(); + } + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture purgeAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(purgeWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable purgeAsync(String fabricName) { + return purgeWithServiceResponseAsync(fabricName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> purgeWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.purge(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginPurge(String fabricName) { + beginPurgeWithServiceResponseAsync(fabricName).toBlocking().single().body(); + } + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginPurgeAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginPurgeWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginPurgeAsync(String fabricName) { + return beginPurgeWithServiceResponseAsync(fabricName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Purges the site. + * The operation to purge(force delete) an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to purge. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginPurgeWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginPurge(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginPurgeDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginPurgeDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner checkConsistency(String fabricName) { + return checkConsistencyWithServiceResponseAsync(fabricName).toBlocking().last().body(); + } + + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture checkConsistencyAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(checkConsistencyWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable checkConsistencyAsync(String fabricName) { + return checkConsistencyWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> checkConsistencyWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.checkConsistency(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner beginCheckConsistency(String fabricName) { + return beginCheckConsistencyWithServiceResponseAsync(fabricName).toBlocking().single().body(); + } + + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCheckConsistencyAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCheckConsistencyWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable beginCheckConsistencyAsync(String fabricName) { + return beginCheckConsistencyWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Checks the consistency of the ASR fabric. + * The operation to perform a consistency check on the fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable> beginCheckConsistencyWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginCheckConsistency(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCheckConsistencyDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCheckConsistencyDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void migrateToAad(String fabricName) { + migrateToAadWithServiceResponseAsync(fabricName).toBlocking().last().body(); + } + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture migrateToAadAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(migrateToAadWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable migrateToAadAsync(String fabricName) { + return migrateToAadWithServiceResponseAsync(fabricName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> migrateToAadWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.migrateToAad(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginMigrateToAad(String fabricName) { + beginMigrateToAadWithServiceResponseAsync(fabricName).toBlocking().single().body(); + } + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginMigrateToAadAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginMigrateToAadWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginMigrateToAadAsync(String fabricName) { + return beginMigrateToAadWithServiceResponseAsync(fabricName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Migrates the site to AAD. + * The operation to migrate an Azure Site Recovery fabric to AAD. + * + * @param fabricName ASR fabric to migrate. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginMigrateToAadWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginMigrateToAad(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginMigrateToAadDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginMigrateToAadDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner reassociateGateway(String fabricName) { + return reassociateGatewayWithServiceResponseAsync(fabricName).toBlocking().last().body(); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture reassociateGatewayAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(reassociateGatewayWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable reassociateGatewayAsync(String fabricName) { + return reassociateGatewayWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> reassociateGatewayWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final FailoverProcessServerRequestProperties properties = null; + FailoverProcessServerRequest failoverProcessServerRequest = new FailoverProcessServerRequest(); + failoverProcessServerRequest.withProperties(null); + Observable> observable = service.reassociateGateway(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), failoverProcessServerRequest, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param properties The properties of the PS Failover request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner reassociateGateway(String fabricName, FailoverProcessServerRequestProperties properties) { + return reassociateGatewayWithServiceResponseAsync(fabricName, properties).toBlocking().last().body(); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param properties The properties of the PS Failover request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture reassociateGatewayAsync(String fabricName, FailoverProcessServerRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(reassociateGatewayWithServiceResponseAsync(fabricName, properties), serviceCallback); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param properties The properties of the PS Failover request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable reassociateGatewayAsync(String fabricName, FailoverProcessServerRequestProperties properties) { + return reassociateGatewayWithServiceResponseAsync(fabricName, properties).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param properties The properties of the PS Failover request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> reassociateGatewayWithServiceResponseAsync(String fabricName, FailoverProcessServerRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + FailoverProcessServerRequest failoverProcessServerRequest = new FailoverProcessServerRequest(); + failoverProcessServerRequest.withProperties(properties); + Observable> observable = service.reassociateGateway(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), failoverProcessServerRequest, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner beginReassociateGateway(String fabricName) { + return beginReassociateGatewayWithServiceResponseAsync(fabricName).toBlocking().single().body(); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginReassociateGatewayAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginReassociateGatewayWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable beginReassociateGatewayAsync(String fabricName) { + return beginReassociateGatewayWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable> beginReassociateGatewayWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final FailoverProcessServerRequestProperties properties = null; + FailoverProcessServerRequest failoverProcessServerRequest = new FailoverProcessServerRequest(); + failoverProcessServerRequest.withProperties(null); + return service.beginReassociateGateway(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), failoverProcessServerRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginReassociateGatewayDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param properties The properties of the PS Failover request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner beginReassociateGateway(String fabricName, FailoverProcessServerRequestProperties properties) { + return beginReassociateGatewayWithServiceResponseAsync(fabricName, properties).toBlocking().single().body(); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param properties The properties of the PS Failover request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginReassociateGatewayAsync(String fabricName, FailoverProcessServerRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginReassociateGatewayWithServiceResponseAsync(fabricName, properties), serviceCallback); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param properties The properties of the PS Failover request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable beginReassociateGatewayAsync(String fabricName, FailoverProcessServerRequestProperties properties) { + return beginReassociateGatewayWithServiceResponseAsync(fabricName, properties).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Perform failover of the process server. + * The operation to move replications from a process server to another process server. + * + * @param fabricName The name of the fabric containing the process server. + * @param properties The properties of the PS Failover request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable> beginReassociateGatewayWithServiceResponseAsync(String fabricName, FailoverProcessServerRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + FailoverProcessServerRequest failoverProcessServerRequest = new FailoverProcessServerRequest(); + failoverProcessServerRequest.withProperties(properties); + return service.beginReassociateGateway(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), failoverProcessServerRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginReassociateGatewayDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginReassociateGatewayDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName) { + deleteWithServiceResponseAsync(fabricName).toBlocking().last().body(); + } + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName) { + return deleteWithServiceResponseAsync(fabricName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName) { + beginDeleteWithServiceResponseAsync(fabricName).toBlocking().single().body(); + } + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName) { + return beginDeleteWithServiceResponseAsync(fabricName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes the site. + * The operation to delete or remove an Azure Site Recovery fabric. + * + * @param fabricName ASR fabric to delete + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner renewCertificate(String fabricName) { + return renewCertificateWithServiceResponseAsync(fabricName).toBlocking().last().body(); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture renewCertificateAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(renewCertificateWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable renewCertificateAsync(String fabricName) { + return renewCertificateWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> renewCertificateWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final RenewCertificateInputProperties properties = null; + RenewCertificateInput renewCertificate = new RenewCertificateInput(); + renewCertificate.withProperties(null); + Observable> observable = service.renewCertificate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), renewCertificate, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param properties Renew certificate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner renewCertificate(String fabricName, RenewCertificateInputProperties properties) { + return renewCertificateWithServiceResponseAsync(fabricName, properties).toBlocking().last().body(); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param properties Renew certificate input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture renewCertificateAsync(String fabricName, RenewCertificateInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(renewCertificateWithServiceResponseAsync(fabricName, properties), serviceCallback); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param properties Renew certificate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable renewCertificateAsync(String fabricName, RenewCertificateInputProperties properties) { + return renewCertificateWithServiceResponseAsync(fabricName, properties).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param properties Renew certificate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> renewCertificateWithServiceResponseAsync(String fabricName, RenewCertificateInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + RenewCertificateInput renewCertificate = new RenewCertificateInput(); + renewCertificate.withProperties(properties); + Observable> observable = service.renewCertificate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), renewCertificate, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner beginRenewCertificate(String fabricName) { + return beginRenewCertificateWithServiceResponseAsync(fabricName).toBlocking().single().body(); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginRenewCertificateAsync(String fabricName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginRenewCertificateWithServiceResponseAsync(fabricName), serviceCallback); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable beginRenewCertificateAsync(String fabricName) { + return beginRenewCertificateWithServiceResponseAsync(fabricName).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable> beginRenewCertificateWithServiceResponseAsync(String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final RenewCertificateInputProperties properties = null; + RenewCertificateInput renewCertificate = new RenewCertificateInput(); + renewCertificate.withProperties(null); + return service.beginRenewCertificate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), renewCertificate, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginRenewCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param properties Renew certificate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the FabricInner object if successful. + */ + public FabricInner beginRenewCertificate(String fabricName, RenewCertificateInputProperties properties) { + return beginRenewCertificateWithServiceResponseAsync(fabricName, properties).toBlocking().single().body(); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param properties Renew certificate input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginRenewCertificateAsync(String fabricName, RenewCertificateInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginRenewCertificateWithServiceResponseAsync(fabricName, properties), serviceCallback); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param properties Renew certificate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable beginRenewCertificateAsync(String fabricName, RenewCertificateInputProperties properties) { + return beginRenewCertificateWithServiceResponseAsync(fabricName, properties).map(new Func1, FabricInner>() { + @Override + public FabricInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Renews certificate for the fabric. + * Renews the connection certificate for the ASR replication fabric. + * + * @param fabricName fabric name to renew certs for. + * @param properties Renew certificate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the FabricInner object + */ + public Observable> beginRenewCertificateWithServiceResponseAsync(String fabricName, RenewCertificateInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + RenewCertificateInput renewCertificate = new RenewCertificateInput(); + renewCertificate.withProperties(properties); + return service.beginRenewCertificate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), renewCertificate, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginRenewCertificateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginRenewCertificateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<FabricInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<FabricInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<FabricInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of ASR fabrics. + * Gets a list of the Azure Site Recovery fabrics in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<FabricInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationJobsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationJobsImpl.java new file mode 100644 index 0000000000000..5892f64c026e2 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationJobsImpl.java @@ -0,0 +1,114 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Job; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.JobQueryParameter; + +class ReplicationJobsImpl extends WrapperImpl implements ReplicationJobs { + private final RecoveryServicesManager manager; + + ReplicationJobsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationJobs()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private JobImpl wrapModel(JobInner inner) { + return new JobImpl(inner, manager()); + } + + @Override + public Observable cancelAsync(String jobName) { + ReplicationJobsInner client = this.inner(); + return client.cancelAsync(jobName) + .map(new Func1() { + @Override + public Job call(JobInner inner) { + return new JobImpl(inner, manager()); + } + }); + } + + @Override + public Observable restartAsync(String jobName) { + ReplicationJobsInner client = this.inner(); + return client.restartAsync(jobName) + .map(new Func1() { + @Override + public Job call(JobInner inner) { + return new JobImpl(inner, manager()); + } + }); + } + + @Override + public Observable resumeAsync(String jobName) { + ReplicationJobsInner client = this.inner(); + return client.resumeAsync(jobName) + .map(new Func1() { + @Override + public Job call(JobInner inner) { + return new JobImpl(inner, manager()); + } + }); + } + + @Override + public Observable exportAsync(JobQueryParameter jobQueryParameter) { + ReplicationJobsInner client = this.inner(); + return client.exportAsync(jobQueryParameter) + .map(new Func1() { + @Override + public Job call(JobInner inner) { + return new JobImpl(inner, manager()); + } + }); + } + + @Override + public Observable listAsync() { + ReplicationJobsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Job call(JobInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String jobName) { + ReplicationJobsInner client = this.inner(); + return client.getAsync(jobName) + .map(new Func1() { + @Override + public Job call(JobInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationJobsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationJobsInner.java new file mode 100644 index 0000000000000..c06782d8dce6a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationJobsInner.java @@ -0,0 +1,1375 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.JobQueryParameter; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ResumeJobParams; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ResumeJobParamsProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationJobs. + */ +public class ReplicationJobsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationJobsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationJobsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationJobsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationJobsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationJobs to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationJobsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Query("$filter") String filter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/{jobName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("jobName") String jobName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs cancel" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/{jobName}/cancel") + Observable> cancel(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("jobName") String jobName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs beginCancel" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/{jobName}/cancel") + Observable> beginCancel(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("jobName") String jobName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs restart" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/{jobName}/restart") + Observable> restart(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("jobName") String jobName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs beginRestart" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/{jobName}/restart") + Observable> beginRestart(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("jobName") String jobName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs resume" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/{jobName}/resume") + Observable> resume(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("jobName") String jobName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ResumeJobParams resumeJobParams, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs beginResume" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/{jobName}/resume") + Observable> beginResume(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("jobName") String jobName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ResumeJobParams resumeJobParams, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs export" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/export") + Observable> export(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Body JobQueryParameter jobQueryParameter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs beginExport" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationJobs/export") + Observable> beginExport(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Body JobQueryParameter jobQueryParameter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationJobs listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<JobInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<JobInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<JobInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<JobInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String filter = null; + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<JobInner> object if successful. + */ + public PagedList list(final String filter) { + ServiceResponse> response = listSinglePageAsync(filter).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param filter OData filter options. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final String filter, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(filter), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<JobInner> object + */ + public Observable> listAsync(final String filter) { + return listWithServiceResponseAsync(filter) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<JobInner> object + */ + public Observable>> listWithServiceResponseAsync(final String filter) { + return listSinglePageAsync(filter) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + ServiceResponse> * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<JobInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String filter) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the job details. + * Get the details of an Azure Site Recovery job. + * + * @param jobName Job identifier + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner get(String jobName) { + return getWithServiceResponseAsync(jobName).toBlocking().single().body(); + } + + /** + * Gets the job details. + * Get the details of an Azure Site Recovery job. + * + * @param jobName Job identifier + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String jobName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(jobName), serviceCallback); + } + + /** + * Gets the job details. + * Get the details of an Azure Site Recovery job. + * + * @param jobName Job identifier + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable getAsync(String jobName) { + return getWithServiceResponseAsync(jobName).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the job details. + * Get the details of an Azure Site Recovery job. + * + * @param jobName Job identifier + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable> getWithServiceResponseAsync(String jobName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner cancel(String jobName) { + return cancelWithServiceResponseAsync(jobName).toBlocking().last().body(); + } + + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture cancelAsync(String jobName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(cancelWithServiceResponseAsync(jobName), serviceCallback); + } + + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable cancelAsync(String jobName) { + return cancelWithServiceResponseAsync(jobName).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> cancelWithServiceResponseAsync(String jobName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.cancel(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner beginCancel(String jobName) { + return beginCancelWithServiceResponseAsync(jobName).toBlocking().single().body(); + } + + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCancelAsync(String jobName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCancelWithServiceResponseAsync(jobName), serviceCallback); + } + + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable beginCancelAsync(String jobName) { + return beginCancelWithServiceResponseAsync(jobName).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Cancels the specified job. + * The operation to cancel an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable> beginCancelWithServiceResponseAsync(String jobName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginCancel(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCancelDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCancelDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner restart(String jobName) { + return restartWithServiceResponseAsync(jobName).toBlocking().last().body(); + } + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture restartAsync(String jobName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(restartWithServiceResponseAsync(jobName), serviceCallback); + } + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable restartAsync(String jobName) { + return restartWithServiceResponseAsync(jobName).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> restartWithServiceResponseAsync(String jobName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.restart(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner beginRestart(String jobName) { + return beginRestartWithServiceResponseAsync(jobName).toBlocking().single().body(); + } + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginRestartAsync(String jobName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginRestartWithServiceResponseAsync(jobName), serviceCallback); + } + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable beginRestartAsync(String jobName) { + return beginRestartWithServiceResponseAsync(jobName).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Restarts the specified job. + * The operation to restart an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable> beginRestartWithServiceResponseAsync(String jobName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginRestart(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginRestartDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginRestartDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner resume(String jobName) { + return resumeWithServiceResponseAsync(jobName).toBlocking().last().body(); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture resumeAsync(String jobName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(resumeWithServiceResponseAsync(jobName), serviceCallback); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable resumeAsync(String jobName) { + return resumeWithServiceResponseAsync(jobName).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> resumeWithServiceResponseAsync(String jobName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final ResumeJobParamsProperties properties = null; + ResumeJobParams resumeJobParams = new ResumeJobParams(); + resumeJobParams.withProperties(null); + Observable> observable = service.resume(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), resumeJobParams, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param properties Resume job properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner resume(String jobName, ResumeJobParamsProperties properties) { + return resumeWithServiceResponseAsync(jobName, properties).toBlocking().last().body(); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param properties Resume job properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture resumeAsync(String jobName, ResumeJobParamsProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(resumeWithServiceResponseAsync(jobName, properties), serviceCallback); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param properties Resume job properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable resumeAsync(String jobName, ResumeJobParamsProperties properties) { + return resumeWithServiceResponseAsync(jobName, properties).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param properties Resume job properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> resumeWithServiceResponseAsync(String jobName, ResumeJobParamsProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + ResumeJobParams resumeJobParams = new ResumeJobParams(); + resumeJobParams.withProperties(properties); + Observable> observable = service.resume(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), resumeJobParams, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner beginResume(String jobName) { + return beginResumeWithServiceResponseAsync(jobName).toBlocking().single().body(); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginResumeAsync(String jobName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginResumeWithServiceResponseAsync(jobName), serviceCallback); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable beginResumeAsync(String jobName) { + return beginResumeWithServiceResponseAsync(jobName).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable> beginResumeWithServiceResponseAsync(String jobName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final ResumeJobParamsProperties properties = null; + ResumeJobParams resumeJobParams = new ResumeJobParams(); + resumeJobParams.withProperties(null); + return service.beginResume(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), resumeJobParams, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginResumeDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param properties Resume job properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner beginResume(String jobName, ResumeJobParamsProperties properties) { + return beginResumeWithServiceResponseAsync(jobName, properties).toBlocking().single().body(); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param properties Resume job properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginResumeAsync(String jobName, ResumeJobParamsProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginResumeWithServiceResponseAsync(jobName, properties), serviceCallback); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param properties Resume job properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable beginResumeAsync(String jobName, ResumeJobParamsProperties properties) { + return beginResumeWithServiceResponseAsync(jobName, properties).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Resumes the specified job. + * The operation to resume an Azure Site Recovery job. + * + * @param jobName Job identifier. + * @param properties Resume job properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable> beginResumeWithServiceResponseAsync(String jobName, ResumeJobParamsProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (jobName == null) { + throw new IllegalArgumentException("Parameter jobName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + ResumeJobParams resumeJobParams = new ResumeJobParams(); + resumeJobParams.withProperties(properties); + return service.beginResume(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), jobName, this.client.apiVersion(), this.client.acceptLanguage(), resumeJobParams, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginResumeDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginResumeDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner export(JobQueryParameter jobQueryParameter) { + return exportWithServiceResponseAsync(jobQueryParameter).toBlocking().last().body(); + } + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture exportAsync(JobQueryParameter jobQueryParameter, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(exportWithServiceResponseAsync(jobQueryParameter), serviceCallback); + } + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable exportAsync(JobQueryParameter jobQueryParameter) { + return exportWithServiceResponseAsync(jobQueryParameter).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> exportWithServiceResponseAsync(JobQueryParameter jobQueryParameter) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (jobQueryParameter == null) { + throw new IllegalArgumentException("Parameter jobQueryParameter is required and cannot be null."); + } + Validator.validate(jobQueryParameter); + Observable> observable = service.export(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), jobQueryParameter, this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the JobInner object if successful. + */ + public JobInner beginExport(JobQueryParameter jobQueryParameter) { + return beginExportWithServiceResponseAsync(jobQueryParameter).toBlocking().single().body(); + } + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginExportAsync(JobQueryParameter jobQueryParameter, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginExportWithServiceResponseAsync(jobQueryParameter), serviceCallback); + } + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable beginExportAsync(JobQueryParameter jobQueryParameter) { + return beginExportWithServiceResponseAsync(jobQueryParameter).map(new Func1, JobInner>() { + @Override + public JobInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Exports the details of the Azure Site Recovery jobs of the vault. + * The operation to export the details of the Azure Site Recovery jobs of the vault. + * + * @param jobQueryParameter job query filter. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the JobInner object + */ + public Observable> beginExportWithServiceResponseAsync(JobQueryParameter jobQueryParameter) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (jobQueryParameter == null) { + throw new IllegalArgumentException("Parameter jobQueryParameter is required and cannot be null."); + } + Validator.validate(jobQueryParameter); + return service.beginExport(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), jobQueryParameter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginExportDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginExportDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<JobInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<JobInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<JobInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of jobs. + * Gets the list of Azure Site Recovery Jobs for the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<JobInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationLogicalNetworksImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationLogicalNetworksImpl.java new file mode 100644 index 0000000000000..4039e7bd31681 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationLogicalNetworksImpl.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationLogicalNetworks; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.LogicalNetwork; + +class ReplicationLogicalNetworksImpl extends WrapperImpl implements ReplicationLogicalNetworks { + private final RecoveryServicesManager manager; + + ReplicationLogicalNetworksImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationLogicalNetworks()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private LogicalNetworkImpl wrapModel(LogicalNetworkInner inner) { + return new LogicalNetworkImpl(inner, manager()); + } + + @Override + public Observable listByReplicationFabricsAsync(final String fabricName) { + ReplicationLogicalNetworksInner client = this.inner(); + return client.listByReplicationFabricsAsync(fabricName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public LogicalNetwork call(LogicalNetworkInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String logicalNetworkName) { + ReplicationLogicalNetworksInner client = this.inner(); + return client.getAsync(fabricName, logicalNetworkName) + .map(new Func1() { + @Override + public LogicalNetwork call(LogicalNetworkInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationLogicalNetworksInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationLogicalNetworksInner.java new file mode 100644 index 0000000000000..df3ff367b21ee --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationLogicalNetworksInner.java @@ -0,0 +1,412 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationLogicalNetworks. + */ +public class ReplicationLogicalNetworksInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationLogicalNetworksService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationLogicalNetworksInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationLogicalNetworksInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationLogicalNetworksService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationLogicalNetworks to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationLogicalNetworksService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationLogicalNetworks listByReplicationFabrics" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationLogicalNetworks") + Observable> listByReplicationFabrics(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationLogicalNetworks get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationLogicalNetworks/{logicalNetworkName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("logicalNetworkName") String logicalNetworkName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationLogicalNetworks listByReplicationFabricsNext" }) + @GET + Observable> listByReplicationFabricsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param fabricName Server Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<LogicalNetworkInner> object if successful. + */ + public PagedList listByReplicationFabrics(final String fabricName) { + ServiceResponse> response = listByReplicationFabricsSinglePageAsync(fabricName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param fabricName Server Id. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsAsync(final String fabricName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsSinglePageAsync(fabricName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param fabricName Server Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<LogicalNetworkInner> object + */ + public Observable> listByReplicationFabricsAsync(final String fabricName) { + return listByReplicationFabricsWithServiceResponseAsync(fabricName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param fabricName Server Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<LogicalNetworkInner> object + */ + public Observable>> listByReplicationFabricsWithServiceResponseAsync(final String fabricName) { + return listByReplicationFabricsSinglePageAsync(fabricName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + ServiceResponse> * @param fabricName Server Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<LogicalNetworkInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsSinglePageAsync(final String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationFabrics(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets a logical network with specified server id and logical network name. + * Gets the details of a logical network. + * + * @param fabricName Server Id. + * @param logicalNetworkName Logical network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the LogicalNetworkInner object if successful. + */ + public LogicalNetworkInner get(String fabricName, String logicalNetworkName) { + return getWithServiceResponseAsync(fabricName, logicalNetworkName).toBlocking().single().body(); + } + + /** + * Gets a logical network with specified server id and logical network name. + * Gets the details of a logical network. + * + * @param fabricName Server Id. + * @param logicalNetworkName Logical network name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String logicalNetworkName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, logicalNetworkName), serviceCallback); + } + + /** + * Gets a logical network with specified server id and logical network name. + * Gets the details of a logical network. + * + * @param fabricName Server Id. + * @param logicalNetworkName Logical network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the LogicalNetworkInner object + */ + public Observable getAsync(String fabricName, String logicalNetworkName) { + return getWithServiceResponseAsync(fabricName, logicalNetworkName).map(new Func1, LogicalNetworkInner>() { + @Override + public LogicalNetworkInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets a logical network with specified server id and logical network name. + * Gets the details of a logical network. + * + * @param fabricName Server Id. + * @param logicalNetworkName Logical network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the LogicalNetworkInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String logicalNetworkName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (logicalNetworkName == null) { + throw new IllegalArgumentException("Parameter logicalNetworkName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, logicalNetworkName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<LogicalNetworkInner> object if successful. + */ + public PagedList listByReplicationFabricsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<LogicalNetworkInner> object + */ + public Observable> listByReplicationFabricsNextAsync(final String nextPageLink) { + return listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<LogicalNetworkInner> object + */ + public Observable>> listByReplicationFabricsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of logical networks under a fabric. + * Lists all the logical networks of the Azure Site Recovery fabric. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<LogicalNetworkInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationFabricsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationMigrationItemsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationMigrationItemsImpl.java new file mode 100644 index 0000000000000..cd104d0283d16 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationMigrationItemsImpl.java @@ -0,0 +1,138 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrationItem; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrateInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestMigrateInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestMigrateCleanupInputProperties; + +class ReplicationMigrationItemsImpl extends WrapperImpl implements ReplicationMigrationItems { + private final RecoveryServicesManager manager; + + ReplicationMigrationItemsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationMigrationItems()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public MigrationItemImpl define(String name) { + return wrapModel(name); + } + + private MigrationItemImpl wrapModel(MigrationItemInner inner) { + return new MigrationItemImpl(inner, manager()); + } + + private MigrationItemImpl wrapModel(String name) { + return new MigrationItemImpl(name, this.manager()); + } + + @Override + public Observable migrateAsync(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties) { + ReplicationMigrationItemsInner client = this.inner(); + return client.migrateAsync(fabricName, protectionContainerName, migrationItemName, properties) + .map(new Func1() { + @Override + public MigrationItem call(MigrationItemInner inner) { + return new MigrationItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable testMigrateAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties) { + ReplicationMigrationItemsInner client = this.inner(); + return client.testMigrateAsync(fabricName, protectionContainerName, migrationItemName, properties) + .map(new Func1() { + @Override + public MigrationItem call(MigrationItemInner inner) { + return new MigrationItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable testMigrateCleanupAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties) { + ReplicationMigrationItemsInner client = this.inner(); + return client.testMigrateCleanupAsync(fabricName, protectionContainerName, migrationItemName, properties) + .map(new Func1() { + @Override + public MigrationItem call(MigrationItemInner inner) { + return new MigrationItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable listAsync() { + ReplicationMigrationItemsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public MigrationItem call(MigrationItemInner inner) { + return new MigrationItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName) { + ReplicationMigrationItemsInner client = this.inner(); + return client.listByReplicationProtectionContainersAsync(fabricName, protectionContainerName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public MigrationItem call(MigrationItemInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String protectionContainerName, String migrationItemName) { + ReplicationMigrationItemsInner client = this.inner(); + return client.getAsync(fabricName, protectionContainerName, migrationItemName) + .map(new Func1() { + @Override + public MigrationItem call(MigrationItemInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable deleteAsync(String fabricName, String protectionContainerName, String migrationItemName) { + ReplicationMigrationItemsInner client = this.inner(); + return client.deleteAsync(fabricName, protectionContainerName, migrationItemName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationMigrationItemsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationMigrationItemsInner.java new file mode 100644 index 0000000000000..b1f6659ae2d6a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationMigrationItemsInner.java @@ -0,0 +1,2445 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EnableMigrationInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EnableMigrationInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrateInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.MigrateInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestMigrateCleanupInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestMigrateCleanupInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestMigrateInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestMigrateInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateMigrationItemInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateMigrationItemInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationMigrationItems. + */ +public class ReplicationMigrationItemsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationMigrationItemsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationMigrationItemsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationMigrationItemsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationMigrationItemsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationMigrationItems to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationMigrationItemsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems listByReplicationProtectionContainers" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems") + Observable> listByReplicationProtectionContainers(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body EnableMigrationInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body EnableMigrationInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems delete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Query("deleteOption") String deleteOption, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems beginDelete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Query("deleteOption") String deleteOption, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems update" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}") + Observable> update(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateMigrationItemInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems beginUpdate" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}") + Observable> beginUpdate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateMigrationItemInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems migrate" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/migrate") + Observable> migrate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body MigrateInput migrateInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems beginMigrate" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/migrate") + Observable> beginMigrate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body MigrateInput migrateInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems testMigrate" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/testMigrate") + Observable> testMigrate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TestMigrateInput testMigrateInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems beginTestMigrate" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/testMigrate") + Observable> beginTestMigrate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TestMigrateInput testMigrateInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems testMigrateCleanup" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/testMigrateCleanup") + Observable> testMigrateCleanup(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TestMigrateCleanupInput testMigrateCleanupInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems beginTestMigrateCleanup" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/testMigrateCleanup") + Observable> beginTestMigrateCleanup(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("migrationItemName") String migrationItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TestMigrateCleanupInput testMigrateCleanupInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationMigrationItems") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Query("skipToken") String skipToken, @Query("$filter") String filter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems listByReplicationProtectionContainersNext" }) + @GET + Observable> listByReplicationProtectionContainersNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationMigrationItems listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<MigrationItemInner> object if successful. + */ + public PagedList listByReplicationProtectionContainers(final String fabricName, final String protectionContainerName) { + ServiceResponse> response = listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName) { + return listByReplicationProtectionContainersWithServiceResponseAsync(fabricName, protectionContainerName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable>> listByReplicationProtectionContainersWithServiceResponseAsync(final String fabricName, final String protectionContainerName) { + return listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + ServiceResponse> * @param fabricName Fabric name. + ServiceResponse> * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<MigrationItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersSinglePageAsync(final String fabricName, final String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationProtectionContainers(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectionContainersDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the details of a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner get(String fabricName, String protectionContainerName, String migrationItemName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).toBlocking().single().body(); + } + + /** + * Gets the details of a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String protectionContainerName, String migrationItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName), serviceCallback); + } + + /** + * Gets the details of a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable getAsync(String fabricName, String protectionContainerName, String migrationItemName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the details of a migration item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Enables migration. + * The operation to create an ASR migration item (enable migration). + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Enable migration input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner create(String fabricName, String protectionContainerName, String migrationItemName, EnableMigrationInputProperties properties) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().last().body(); + } + + /** + * Enables migration. + * The operation to create an ASR migration item (enable migration). + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Enable migration input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String protectionContainerName, String migrationItemName, EnableMigrationInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Enables migration. + * The operation to create an ASR migration item (enable migration). + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Enable migration input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String protectionContainerName, String migrationItemName, EnableMigrationInputProperties properties) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Enables migration. + * The operation to create an ASR migration item (enable migration). + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Enable migration input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, EnableMigrationInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + EnableMigrationInput input = new EnableMigrationInput(); + input.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Enables migration. + * The operation to create an ASR migration item (enable migration). + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Enable migration input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner beginCreate(String fabricName, String protectionContainerName, String migrationItemName, EnableMigrationInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().single().body(); + } + + /** + * Enables migration. + * The operation to create an ASR migration item (enable migration). + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Enable migration input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String protectionContainerName, String migrationItemName, EnableMigrationInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Enables migration. + * The operation to create an ASR migration item (enable migration). + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Enable migration input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable beginCreateAsync(String fabricName, String protectionContainerName, String migrationItemName, EnableMigrationInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Enables migration. + * The operation to create an ASR migration item (enable migration). + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Enable migration input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, EnableMigrationInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + EnableMigrationInput input = new EnableMigrationInput(); + input.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String protectionContainerName, String migrationItemName) { + deleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).toBlocking().last().body(); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String protectionContainerName, String migrationItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName), serviceCallback); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String protectionContainerName, String migrationItemName) { + return deleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String deleteOption = null; + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), deleteOption, this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param deleteOption The delete option. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String protectionContainerName, String migrationItemName, String deleteOption) { + deleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, deleteOption).toBlocking().last().body(); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param deleteOption The delete option. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String protectionContainerName, String migrationItemName, String deleteOption, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, deleteOption), serviceCallback); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param deleteOption The delete option. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String protectionContainerName, String migrationItemName, String deleteOption) { + return deleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, deleteOption).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param deleteOption The delete option. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, String deleteOption) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), deleteOption, this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String protectionContainerName, String migrationItemName) { + beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).toBlocking().single().body(); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String protectionContainerName, String migrationItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName), serviceCallback); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String protectionContainerName, String migrationItemName) { + return beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String deleteOption = null; + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), deleteOption, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param deleteOption The delete option. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String protectionContainerName, String migrationItemName, String deleteOption) { + beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, deleteOption).toBlocking().single().body(); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param deleteOption The delete option. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String protectionContainerName, String migrationItemName, String deleteOption, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, deleteOption), serviceCallback); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param deleteOption The delete option. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String protectionContainerName, String migrationItemName, String deleteOption) { + return beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, deleteOption).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete the migration item. + * The operation to delete an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param deleteOption The delete option. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, String deleteOption) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), deleteOption, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner update(String fabricName, String protectionContainerName, String migrationItemName) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).toBlocking().last().body(); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String protectionContainerName, String migrationItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName), serviceCallback); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String protectionContainerName, String migrationItemName) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateMigrationItemInputProperties properties = null; + UpdateMigrationItemInput input = new UpdateMigrationItemInput(); + input.withProperties(null); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Update migration item input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner update(String fabricName, String protectionContainerName, String migrationItemName, UpdateMigrationItemInputProperties properties) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().last().body(); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Update migration item input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String protectionContainerName, String migrationItemName, UpdateMigrationItemInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Update migration item input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String protectionContainerName, String migrationItemName, UpdateMigrationItemInputProperties properties) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Update migration item input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, UpdateMigrationItemInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateMigrationItemInput input = new UpdateMigrationItemInput(); + input.withProperties(properties); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner beginUpdate(String fabricName, String protectionContainerName, String migrationItemName) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).toBlocking().single().body(); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String protectionContainerName, String migrationItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName), serviceCallback); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable beginUpdateAsync(String fabricName, String protectionContainerName, String migrationItemName) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateMigrationItemInputProperties properties = null; + UpdateMigrationItemInput input = new UpdateMigrationItemInput(); + input.withProperties(null); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Update migration item input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner beginUpdate(String fabricName, String protectionContainerName, String migrationItemName, UpdateMigrationItemInputProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().single().body(); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Update migration item input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String protectionContainerName, String migrationItemName, UpdateMigrationItemInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Update migration item input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable beginUpdateAsync(String fabricName, String protectionContainerName, String migrationItemName, UpdateMigrationItemInputProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates migration item. + * The operation to update the recovery settings of an ASR migration item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Update migration item input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, UpdateMigrationItemInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateMigrationItemInput input = new UpdateMigrationItemInput(); + input.withProperties(properties); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner migrate(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties) { + return migrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().last().body(); + } + + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture migrateAsync(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(migrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable migrateAsync(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties) { + return migrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> migrateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + MigrateInput migrateInput = new MigrateInput(); + migrateInput.withProperties(properties); + Observable> observable = service.migrate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), migrateInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner beginMigrate(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties) { + return beginMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().single().body(); + } + + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginMigrateAsync(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable beginMigrateAsync(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties) { + return beginMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Migrate item. + * The operation to initiate migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable> beginMigrateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, MigrateInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + MigrateInput migrateInput = new MigrateInput(); + migrateInput.withProperties(properties); + return service.beginMigrate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), migrateInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginMigrateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginMigrateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner testMigrate(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties) { + return testMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().last().body(); + } + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture testMigrateAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(testMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable testMigrateAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties) { + return testMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> testMigrateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + TestMigrateInput testMigrateInput = new TestMigrateInput(); + testMigrateInput.withProperties(properties); + Observable> observable = service.testMigrate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), testMigrateInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner beginTestMigrate(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties) { + return beginTestMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().single().body(); + } + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginTestMigrateAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginTestMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable beginTestMigrateAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties) { + return beginTestMigrateWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Test migrate item. + * The operation to initiate test migration of the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable> beginTestMigrateWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + TestMigrateInput testMigrateInput = new TestMigrateInput(); + testMigrateInput.withProperties(properties); + return service.beginTestMigrate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), testMigrateInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginTestMigrateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginTestMigrateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner testMigrateCleanup(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties) { + return testMigrateCleanupWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().last().body(); + } + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture testMigrateCleanupAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(testMigrateCleanupWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable testMigrateCleanupAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties) { + return testMigrateCleanupWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> testMigrateCleanupWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + TestMigrateCleanupInput testMigrateCleanupInput = new TestMigrateCleanupInput(); + testMigrateCleanupInput.withProperties(properties); + Observable> observable = service.testMigrateCleanup(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), testMigrateCleanupInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the MigrationItemInner object if successful. + */ + public MigrationItemInner beginTestMigrateCleanup(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties) { + return beginTestMigrateCleanupWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).toBlocking().single().body(); + } + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginTestMigrateCleanupAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginTestMigrateCleanupWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties), serviceCallback); + } + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable beginTestMigrateCleanupAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties) { + return beginTestMigrateCleanupWithServiceResponseAsync(fabricName, protectionContainerName, migrationItemName, properties).map(new Func1, MigrationItemInner>() { + @Override + public MigrationItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Test migrate cleanup. + * The operation to initiate test migrate cleanup. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param migrationItemName Migration item name. + * @param properties Test migrate cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the MigrationItemInner object + */ + public Observable> beginTestMigrateCleanupWithServiceResponseAsync(String fabricName, String protectionContainerName, String migrationItemName, TestMigrateCleanupInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (migrationItemName == null) { + throw new IllegalArgumentException("Parameter migrationItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + TestMigrateCleanupInput testMigrateCleanupInput = new TestMigrateCleanupInput(); + testMigrateCleanupInput.withProperties(properties); + return service.beginTestMigrateCleanup(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, migrationItemName, this.client.apiVersion(), this.client.acceptLanguage(), testMigrateCleanupInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginTestMigrateCleanupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginTestMigrateCleanupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of migration items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<MigrationItemInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of migration items in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of migration items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of migration items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of migration items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<MigrationItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String skipToken = null; + final String filter = null; + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), skipToken, filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets the list of migration items in the vault. + * + * @param skipToken The pagination token. + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<MigrationItemInner> object if successful. + */ + public PagedList list(final String skipToken, final String filter) { + ServiceResponse> response = listSinglePageAsync(skipToken, filter).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of migration items in the vault. + * + * @param skipToken The pagination token. + * @param filter OData filter options. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final String skipToken, final String filter, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(skipToken, filter), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of migration items in the vault. + * + * @param skipToken The pagination token. + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable> listAsync(final String skipToken, final String filter) { + return listWithServiceResponseAsync(skipToken, filter) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of migration items in the vault. + * + * @param skipToken The pagination token. + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable>> listWithServiceResponseAsync(final String skipToken, final String filter) { + return listSinglePageAsync(skipToken, filter) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of migration items in the vault. + * + ServiceResponse> * @param skipToken The pagination token. + ServiceResponse> * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<MigrationItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String skipToken, final String filter) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), skipToken, filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<MigrationItemInner> object if successful. + */ + public PagedList listByReplicationProtectionContainersNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable> listByReplicationProtectionContainersNextAsync(final String nextPageLink) { + return listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable>> listByReplicationProtectionContainersNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of migration items in the protection container. + * Gets the list of ASR migration items in the protection container. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<MigrationItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationProtectionContainersNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectionContainersNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of migration items in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<MigrationItemInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of migration items in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of migration items in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of migration items in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<MigrationItemInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of migration items in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<MigrationItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworkMappingsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworkMappingsImpl.java new file mode 100644 index 0000000000000..49799c89c5b78 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworkMappingsImpl.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.NetworkMapping; + +class ReplicationNetworkMappingsImpl extends WrapperImpl implements ReplicationNetworkMappings { + private final RecoveryServicesManager manager; + + ReplicationNetworkMappingsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationNetworkMappings()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public NetworkMappingImpl define(String name) { + return wrapModel(name); + } + + private NetworkMappingImpl wrapModel(NetworkMappingInner inner) { + return new NetworkMappingImpl(inner, manager()); + } + + private NetworkMappingImpl wrapModel(String name) { + return new NetworkMappingImpl(name, this.manager()); + } + + @Override + public Observable listAsync() { + ReplicationNetworkMappingsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public NetworkMapping call(NetworkMappingInner inner) { + return new NetworkMappingImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationNetworksAsync(final String fabricName, final String networkName) { + ReplicationNetworkMappingsInner client = this.inner(); + return client.listByReplicationNetworksAsync(fabricName, networkName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public NetworkMapping call(NetworkMappingInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String networkName, String networkMappingName) { + ReplicationNetworkMappingsInner client = this.inner(); + return client.getAsync(fabricName, networkName, networkMappingName) + .map(new Func1() { + @Override + public NetworkMapping call(NetworkMappingInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable deleteAsync(String fabricName, String networkName, String networkMappingName) { + ReplicationNetworkMappingsInner client = this.inner(); + return client.deleteAsync(fabricName, networkName, networkMappingName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworkMappingsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworkMappingsInner.java new file mode 100644 index 0000000000000..568b12a577259 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworkMappingsInner.java @@ -0,0 +1,1672 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateNetworkMappingInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateNetworkMappingInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateNetworkMappingInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateNetworkMappingInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationNetworkMappings. + */ +public class ReplicationNetworkMappingsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationNetworkMappingsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationNetworkMappingsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationNetworkMappingsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationNetworkMappingsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationNetworkMappings to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationNetworkMappingsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings listByReplicationNetworks" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings") + Observable> listByReplicationNetworks(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Path("networkMappingName") String networkMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Path("networkMappingName") String networkMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateNetworkMappingInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Path("networkMappingName") String networkMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateNetworkMappingInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings delete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Path("networkMappingName") String networkMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings beginDelete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Path("networkMappingName") String networkMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings update" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}") + Observable> update(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Path("networkMappingName") String networkMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateNetworkMappingInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings beginUpdate" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}") + Observable> beginUpdate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Path("networkMappingName") String networkMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateNetworkMappingInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationNetworkMappings") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings listByReplicationNetworksNext" }) + @GET + Observable> listByReplicationNetworksNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworkMappings listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<NetworkMappingInner> object if successful. + */ + public PagedList listByReplicationNetworks(final String fabricName, final String networkName) { + ServiceResponse> response = listByReplicationNetworksSinglePageAsync(fabricName, networkName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationNetworksNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationNetworksAsync(final String fabricName, final String networkName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationNetworksSinglePageAsync(fabricName, networkName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationNetworksNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkMappingInner> object + */ + public Observable> listByReplicationNetworksAsync(final String fabricName, final String networkName) { + return listByReplicationNetworksWithServiceResponseAsync(fabricName, networkName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkMappingInner> object + */ + public Observable>> listByReplicationNetworksWithServiceResponseAsync(final String fabricName, final String networkName) { + return listByReplicationNetworksSinglePageAsync(fabricName, networkName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationNetworksNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + ServiceResponse> * @param fabricName Primary fabric name. + ServiceResponse> * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<NetworkMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationNetworksSinglePageAsync(final String fabricName, final String networkName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationNetworks(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationNetworksDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationNetworksDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets network mapping by name. + * Gets the details of an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner get(String fabricName, String networkName, String networkMappingName) { + return getWithServiceResponseAsync(fabricName, networkName, networkMappingName).toBlocking().single().body(); + } + + /** + * Gets network mapping by name. + * Gets the details of an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String networkName, String networkMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, networkName, networkMappingName), serviceCallback); + } + + /** + * Gets network mapping by name. + * Gets the details of an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable getAsync(String fabricName, String networkName, String networkMappingName) { + return getWithServiceResponseAsync(fabricName, networkName, networkMappingName).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets network mapping by name. + * Gets the details of an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner create(String fabricName, String networkName, String networkMappingName) { + return createWithServiceResponseAsync(fabricName, networkName, networkMappingName).toBlocking().last().body(); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String networkName, String networkMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, networkName, networkMappingName), serviceCallback); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String networkName, String networkMappingName) { + return createWithServiceResponseAsync(fabricName, networkName, networkMappingName).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final CreateNetworkMappingInputProperties properties = null; + CreateNetworkMappingInput input = new CreateNetworkMappingInput(); + input.withProperties(null); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties Input properties for creating network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner create(String fabricName, String networkName, String networkMappingName, CreateNetworkMappingInputProperties properties) { + return createWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties).toBlocking().last().body(); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties Input properties for creating network mapping. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String networkName, String networkMappingName, CreateNetworkMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties), serviceCallback); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties Input properties for creating network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String networkName, String networkMappingName, CreateNetworkMappingInputProperties properties) { + return createWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties Input properties for creating network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName, CreateNetworkMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + CreateNetworkMappingInput input = new CreateNetworkMappingInput(); + input.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner beginCreate(String fabricName, String networkName, String networkMappingName) { + return beginCreateWithServiceResponseAsync(fabricName, networkName, networkMappingName).toBlocking().single().body(); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String networkName, String networkMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, networkName, networkMappingName), serviceCallback); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable beginCreateAsync(String fabricName, String networkName, String networkMappingName) { + return beginCreateWithServiceResponseAsync(fabricName, networkName, networkMappingName).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final CreateNetworkMappingInputProperties properties = null; + CreateNetworkMappingInput input = new CreateNetworkMappingInput(); + input.withProperties(null); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties Input properties for creating network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner beginCreate(String fabricName, String networkName, String networkMappingName, CreateNetworkMappingInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties).toBlocking().single().body(); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties Input properties for creating network mapping. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String networkName, String networkMappingName, CreateNetworkMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties), serviceCallback); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties Input properties for creating network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable beginCreateAsync(String fabricName, String networkName, String networkMappingName, CreateNetworkMappingInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates network mapping. + * The operation to create an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties Input properties for creating network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName, CreateNetworkMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + CreateNetworkMappingInput input = new CreateNetworkMappingInput(); + input.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String networkName, String networkMappingName) { + deleteWithServiceResponseAsync(fabricName, networkName, networkMappingName).toBlocking().last().body(); + } + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String networkName, String networkMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, networkName, networkMappingName), serviceCallback); + } + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String networkName, String networkMappingName) { + return deleteWithServiceResponseAsync(fabricName, networkName, networkMappingName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String networkName, String networkMappingName) { + beginDeleteWithServiceResponseAsync(fabricName, networkName, networkMappingName).toBlocking().single().body(); + } + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String networkName, String networkMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, networkName, networkMappingName), serviceCallback); + } + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String networkName, String networkMappingName) { + return beginDeleteWithServiceResponseAsync(fabricName, networkName, networkMappingName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete network mapping. + * The operation to delete a network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName ARM Resource Name for network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner update(String fabricName, String networkName, String networkMappingName) { + return updateWithServiceResponseAsync(fabricName, networkName, networkMappingName).toBlocking().last().body(); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String networkName, String networkMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, networkName, networkMappingName), serviceCallback); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String networkName, String networkMappingName) { + return updateWithServiceResponseAsync(fabricName, networkName, networkMappingName).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateNetworkMappingInputProperties properties = null; + UpdateNetworkMappingInput input = new UpdateNetworkMappingInput(); + input.withProperties(null); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties The input properties needed to update network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner update(String fabricName, String networkName, String networkMappingName, UpdateNetworkMappingInputProperties properties) { + return updateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties).toBlocking().last().body(); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties The input properties needed to update network mapping. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String networkName, String networkMappingName, UpdateNetworkMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties), serviceCallback); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties The input properties needed to update network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String networkName, String networkMappingName, UpdateNetworkMappingInputProperties properties) { + return updateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties The input properties needed to update network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName, UpdateNetworkMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateNetworkMappingInput input = new UpdateNetworkMappingInput(); + input.withProperties(properties); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner beginUpdate(String fabricName, String networkName, String networkMappingName) { + return beginUpdateWithServiceResponseAsync(fabricName, networkName, networkMappingName).toBlocking().single().body(); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String networkName, String networkMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, networkName, networkMappingName), serviceCallback); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable beginUpdateAsync(String fabricName, String networkName, String networkMappingName) { + return beginUpdateWithServiceResponseAsync(fabricName, networkName, networkMappingName).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateNetworkMappingInputProperties properties = null; + UpdateNetworkMappingInput input = new UpdateNetworkMappingInput(); + input.withProperties(null); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties The input properties needed to update network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkMappingInner object if successful. + */ + public NetworkMappingInner beginUpdate(String fabricName, String networkName, String networkMappingName, UpdateNetworkMappingInputProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties).toBlocking().single().body(); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties The input properties needed to update network mapping. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String networkName, String networkMappingName, UpdateNetworkMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties), serviceCallback); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties The input properties needed to update network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable beginUpdateAsync(String fabricName, String networkName, String networkMappingName, UpdateNetworkMappingInputProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, networkName, networkMappingName, properties).map(new Func1, NetworkMappingInner>() { + @Override + public NetworkMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates network mapping. + * The operation to update an ASR network mapping. + * + * @param fabricName Primary fabric name. + * @param networkName Primary network name. + * @param networkMappingName Network mapping name. + * @param properties The input properties needed to update network mapping. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkMappingInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String networkName, String networkMappingName, UpdateNetworkMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (networkMappingName == null) { + throw new IllegalArgumentException("Parameter networkMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateNetworkMappingInput input = new UpdateNetworkMappingInput(); + input.withProperties(properties); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, networkMappingName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<NetworkMappingInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkMappingInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkMappingInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<NetworkMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<NetworkMappingInner> object if successful. + */ + public PagedList listByReplicationNetworksNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationNetworksNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationNetworksNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationNetworksNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationNetworksNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationNetworksNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkMappingInner> object + */ + public Observable> listByReplicationNetworksNextAsync(final String nextPageLink) { + return listByReplicationNetworksNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkMappingInner> object + */ + public Observable>> listByReplicationNetworksNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationNetworksNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationNetworksNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all the network mappings under a network. + * Lists all ASR network mappings for the specified network. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<NetworkMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationNetworksNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationNetworksNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationNetworksNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationNetworksNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<NetworkMappingInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkMappingInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkMappingInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all the network mappings under a vault. + * Lists all ASR network mappings in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<NetworkMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworksImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworksImpl.java new file mode 100644 index 0000000000000..dc11fe2060e9a --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworksImpl.java @@ -0,0 +1,83 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworks; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Network; + +class ReplicationNetworksImpl extends WrapperImpl implements ReplicationNetworks { + private final RecoveryServicesManager manager; + + ReplicationNetworksImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationNetworks()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private NetworkImpl wrapModel(NetworkInner inner) { + return new NetworkImpl(inner, manager()); + } + + @Override + public Observable listAsync() { + ReplicationNetworksInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Network call(NetworkInner inner) { + return new NetworkImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationFabricsAsync(final String fabricName) { + ReplicationNetworksInner client = this.inner(); + return client.listByReplicationFabricsAsync(fabricName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Network call(NetworkInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String networkName) { + ReplicationNetworksInner client = this.inner(); + return client.getAsync(fabricName, networkName) + .map(new Func1() { + @Override + public Network call(NetworkInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworksInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworksInner.java new file mode 100644 index 0000000000000..48cb656a28ed5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationNetworksInner.java @@ -0,0 +1,654 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationNetworks. + */ +public class ReplicationNetworksInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationNetworksService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationNetworksInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationNetworksInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationNetworksService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationNetworks to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationNetworksService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworks listByReplicationFabrics" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks") + Observable> listByReplicationFabrics(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworks get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("networkName") String networkName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworks list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationNetworks") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworks listByReplicationFabricsNext" }) + @GET + Observable> listByReplicationFabricsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationNetworks listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<NetworkInner> object if successful. + */ + public PagedList listByReplicationFabrics(final String fabricName) { + ServiceResponse> response = listByReplicationFabricsSinglePageAsync(fabricName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param fabricName Fabric name + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsAsync(final String fabricName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsSinglePageAsync(fabricName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkInner> object + */ + public Observable> listByReplicationFabricsAsync(final String fabricName) { + return listByReplicationFabricsWithServiceResponseAsync(fabricName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkInner> object + */ + public Observable>> listByReplicationFabricsWithServiceResponseAsync(final String fabricName) { + return listByReplicationFabricsSinglePageAsync(fabricName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + ServiceResponse> * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<NetworkInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsSinglePageAsync(final String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationFabrics(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets a network with specified server id and network name. + * Gets the details of a network. + * + * @param fabricName Server Id. + * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetworkInner object if successful. + */ + public NetworkInner get(String fabricName, String networkName) { + return getWithServiceResponseAsync(fabricName, networkName).toBlocking().single().body(); + } + + /** + * Gets a network with specified server id and network name. + * Gets the details of a network. + * + * @param fabricName Server Id. + * @param networkName Primary network name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String networkName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, networkName), serviceCallback); + } + + /** + * Gets a network with specified server id and network name. + * Gets the details of a network. + * + * @param fabricName Server Id. + * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkInner object + */ + public Observable getAsync(String fabricName, String networkName) { + return getWithServiceResponseAsync(fabricName, networkName).map(new Func1, NetworkInner>() { + @Override + public NetworkInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets a network with specified server id and network name. + * Gets the details of a network. + * + * @param fabricName Server Id. + * @param networkName Primary network name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetworkInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String networkName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (networkName == null) { + throw new IllegalArgumentException("Parameter networkName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, networkName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<NetworkInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<NetworkInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<NetworkInner> object if successful. + */ + public PagedList listByReplicationFabricsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkInner> object + */ + public Observable> listByReplicationFabricsNextAsync(final String nextPageLink) { + return listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkInner> object + */ + public Observable>> listByReplicationFabricsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of networks under a fabric. + * Lists the networks available for a fabric. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<NetworkInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationFabricsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<NetworkInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<NetworkInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of networks. View-only API. + * Lists the networks available in a vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<NetworkInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationPoliciesImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationPoliciesImpl.java new file mode 100644 index 0000000000000..1860cccd3f648 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationPoliciesImpl.java @@ -0,0 +1,81 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Policy; + +class ReplicationPoliciesImpl extends WrapperImpl implements ReplicationPolicies { + private final RecoveryServicesManager manager; + + ReplicationPoliciesImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationPolicies()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public PolicyImpl define(String name) { + return wrapModel(name); + } + + private PolicyImpl wrapModel(PolicyInner inner) { + return new PolicyImpl(inner, manager()); + } + + private PolicyImpl wrapModel(String name) { + return new PolicyImpl(name, this.manager()); + } + + @Override + public Observable listAsync() { + ReplicationPoliciesInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Policy call(PolicyInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String policyName) { + ReplicationPoliciesInner client = this.inner(); + return client.getAsync(policyName) + .map(new Func1() { + @Override + public Policy call(PolicyInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable deleteAsync(String policyName) { + ReplicationPoliciesInner client = this.inner(); + return client.deleteAsync(policyName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationPoliciesInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationPoliciesInner.java new file mode 100644 index 0000000000000..7aa1e83db4d76 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationPoliciesInner.java @@ -0,0 +1,1260 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreatePolicyInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreatePolicyInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdatePolicyInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdatePolicyInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationPolicies. + */ +public class ReplicationPoliciesInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationPoliciesService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationPoliciesInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationPoliciesInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationPoliciesService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationPolicies to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationPoliciesService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("policyName") String policyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("policyName") String policyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreatePolicyInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("policyName") String policyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreatePolicyInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies delete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("policyName") String policyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies beginDelete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("policyName") String policyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies update" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}") + Observable> update(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("policyName") String policyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdatePolicyInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies beginUpdate" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}") + Observable> beginUpdate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("policyName") String policyName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdatePolicyInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationPolicies listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the requested policy. + * Gets the details of a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner get(String policyName) { + return getWithServiceResponseAsync(policyName).toBlocking().single().body(); + } + + /** + * Gets the requested policy. + * Gets the details of a replication policy. + * + * @param policyName Replication policy name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String policyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(policyName), serviceCallback); + } + + /** + * Gets the requested policy. + * Gets the details of a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable getAsync(String policyName) { + return getWithServiceResponseAsync(policyName).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the requested policy. + * Gets the details of a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable> getWithServiceResponseAsync(String policyName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner create(String policyName) { + return createWithServiceResponseAsync(policyName).toBlocking().last().body(); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String policyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(policyName), serviceCallback); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String policyName) { + return createWithServiceResponseAsync(policyName).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String policyName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final CreatePolicyInputProperties properties = null; + CreatePolicyInput input = new CreatePolicyInput(); + input.withProperties(null); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param properties Policy creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner create(String policyName, CreatePolicyInputProperties properties) { + return createWithServiceResponseAsync(policyName, properties).toBlocking().last().body(); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param properties Policy creation properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String policyName, CreatePolicyInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(policyName, properties), serviceCallback); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param properties Policy creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String policyName, CreatePolicyInputProperties properties) { + return createWithServiceResponseAsync(policyName, properties).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param properties Policy creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String policyName, CreatePolicyInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + CreatePolicyInput input = new CreatePolicyInput(); + input.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner beginCreate(String policyName) { + return beginCreateWithServiceResponseAsync(policyName).toBlocking().single().body(); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String policyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(policyName), serviceCallback); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable beginCreateAsync(String policyName) { + return beginCreateWithServiceResponseAsync(policyName).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String policyName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final CreatePolicyInputProperties properties = null; + CreatePolicyInput input = new CreatePolicyInput(); + input.withProperties(null); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param properties Policy creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner beginCreate(String policyName, CreatePolicyInputProperties properties) { + return beginCreateWithServiceResponseAsync(policyName, properties).toBlocking().single().body(); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param properties Policy creation properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String policyName, CreatePolicyInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(policyName, properties), serviceCallback); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param properties Policy creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable beginCreateAsync(String policyName, CreatePolicyInputProperties properties) { + return beginCreateWithServiceResponseAsync(policyName, properties).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates the policy. + * The operation to create a replication policy. + * + * @param policyName Replication policy name + * @param properties Policy creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String policyName, CreatePolicyInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + CreatePolicyInput input = new CreatePolicyInput(); + input.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String policyName) { + deleteWithServiceResponseAsync(policyName).toBlocking().last().body(); + } + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String policyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(policyName), serviceCallback); + } + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String policyName) { + return deleteWithServiceResponseAsync(policyName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String policyName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String policyName) { + beginDeleteWithServiceResponseAsync(policyName).toBlocking().single().body(); + } + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String policyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(policyName), serviceCallback); + } + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String policyName) { + return beginDeleteWithServiceResponseAsync(policyName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete the policy. + * The operation to delete a replication policy. + * + * @param policyName Replication policy name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String policyName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner update(String policyName) { + return updateWithServiceResponseAsync(policyName).toBlocking().last().body(); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String policyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(policyName), serviceCallback); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String policyName) { + return updateWithServiceResponseAsync(policyName).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String policyName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdatePolicyInputProperties properties = null; + UpdatePolicyInput input = new UpdatePolicyInput(); + input.withProperties(null); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param properties The ReplicationProviderSettings. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner update(String policyName, UpdatePolicyInputProperties properties) { + return updateWithServiceResponseAsync(policyName, properties).toBlocking().last().body(); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param properties The ReplicationProviderSettings. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String policyName, UpdatePolicyInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(policyName, properties), serviceCallback); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param properties The ReplicationProviderSettings. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String policyName, UpdatePolicyInputProperties properties) { + return updateWithServiceResponseAsync(policyName, properties).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param properties The ReplicationProviderSettings. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String policyName, UpdatePolicyInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdatePolicyInput input = new UpdatePolicyInput(); + input.withProperties(properties); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner beginUpdate(String policyName) { + return beginUpdateWithServiceResponseAsync(policyName).toBlocking().single().body(); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String policyName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(policyName), serviceCallback); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable beginUpdateAsync(String policyName) { + return beginUpdateWithServiceResponseAsync(policyName).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String policyName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdatePolicyInputProperties properties = null; + UpdatePolicyInput input = new UpdatePolicyInput(); + input.withProperties(null); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param properties The ReplicationProviderSettings. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyInner object if successful. + */ + public PolicyInner beginUpdate(String policyName, UpdatePolicyInputProperties properties) { + return beginUpdateWithServiceResponseAsync(policyName, properties).toBlocking().single().body(); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param properties The ReplicationProviderSettings. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String policyName, UpdatePolicyInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(policyName, properties), serviceCallback); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param properties The ReplicationProviderSettings. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable beginUpdateAsync(String policyName, UpdatePolicyInputProperties properties) { + return beginUpdateWithServiceResponseAsync(policyName, properties).map(new Func1, PolicyInner>() { + @Override + public PolicyInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the policy. + * The operation to update a replication policy. + * + * @param policyName Policy Id. + * @param properties The ReplicationProviderSettings. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String policyName, UpdatePolicyInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (policyName == null) { + throw new IllegalArgumentException("Parameter policyName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdatePolicyInput input = new UpdatePolicyInput(); + input.withProperties(properties); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), policyName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of replication policies. + * Lists the replication policies for a vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectableItemsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectableItemsImpl.java new file mode 100644 index 0000000000000..9fa1b725b101c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectableItemsImpl.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectableItems; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectableItem; + +class ReplicationProtectableItemsImpl extends WrapperImpl implements ReplicationProtectableItems { + private final RecoveryServicesManager manager; + + ReplicationProtectableItemsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationProtectableItems()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private ProtectableItemImpl wrapModel(ProtectableItemInner inner) { + return new ProtectableItemImpl(inner, manager()); + } + + @Override + public Observable listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName) { + ReplicationProtectableItemsInner client = this.inner(); + return client.listByReplicationProtectionContainersAsync(fabricName, protectionContainerName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public ProtectableItem call(ProtectableItemInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String protectionContainerName, String protectableItemName) { + ReplicationProtectableItemsInner client = this.inner(); + return client.getAsync(fabricName, protectionContainerName, protectableItemName) + .map(new Func1() { + @Override + public ProtectableItem call(ProtectableItemInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectableItemsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectableItemsInner.java new file mode 100644 index 0000000000000..297f719c82006 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectableItemsInner.java @@ -0,0 +1,560 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationProtectableItems. + */ +public class ReplicationProtectableItemsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationProtectableItemsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationProtectableItemsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationProtectableItemsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationProtectableItemsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationProtectableItems to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationProtectableItemsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectableItems listByReplicationProtectionContainers" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectableItems") + Observable> listByReplicationProtectionContainers(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Query("$filter") String filter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectableItems get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectableItems/{protectableItemName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("protectableItemName") String protectableItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectableItems listByReplicationProtectionContainersNext" }) + @GET + Observable> listByReplicationProtectionContainersNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectableItemInner> object if successful. + */ + public PagedList listByReplicationProtectionContainers(final String fabricName, final String protectionContainerName) { + ServiceResponse> response = listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectableItemInner> object + */ + public Observable> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName) { + return listByReplicationProtectionContainersWithServiceResponseAsync(fabricName, protectionContainerName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectableItemInner> object + */ + public Observable>> listByReplicationProtectionContainersWithServiceResponseAsync(final String fabricName, final String protectionContainerName) { + return listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectableItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersSinglePageAsync(final String fabricName, final String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String filter = null; + return service.listByReplicationProtectionContainers(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectableItemInner> object if successful. + */ + public PagedList listByReplicationProtectionContainers(final String fabricName, final String protectionContainerName, final String filter) { + ServiceResponse> response = listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName, filter).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param filter OData filter options. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName, final String filter, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName, filter), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectableItemInner> object + */ + public Observable> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName, final String filter) { + return listByReplicationProtectionContainersWithServiceResponseAsync(fabricName, protectionContainerName, filter) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectableItemInner> object + */ + public Observable>> listByReplicationProtectionContainersWithServiceResponseAsync(final String fabricName, final String protectionContainerName, final String filter) { + return listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName, filter) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + ServiceResponse> * @param fabricName Fabric name. + ServiceResponse> * @param protectionContainerName Protection container name. + ServiceResponse> * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectableItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersSinglePageAsync(final String fabricName, final String protectionContainerName, final String filter) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationProtectionContainers(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectionContainersDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the details of a protectable item. + * The operation to get the details of a protectable item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param protectableItemName Protectable item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectableItemInner object if successful. + */ + public ProtectableItemInner get(String fabricName, String protectionContainerName, String protectableItemName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, protectableItemName).toBlocking().single().body(); + } + + /** + * Gets the details of a protectable item. + * The operation to get the details of a protectable item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param protectableItemName Protectable item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String protectionContainerName, String protectableItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, protectionContainerName, protectableItemName), serviceCallback); + } + + /** + * Gets the details of a protectable item. + * The operation to get the details of a protectable item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param protectableItemName Protectable item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectableItemInner object + */ + public Observable getAsync(String fabricName, String protectionContainerName, String protectableItemName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, protectableItemName).map(new Func1, ProtectableItemInner>() { + @Override + public ProtectableItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the details of a protectable item. + * The operation to get the details of a protectable item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param protectableItemName Protectable item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectableItemInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String protectionContainerName, String protectableItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (protectableItemName == null) { + throw new IllegalArgumentException("Parameter protectableItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, protectableItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectableItemInner> object if successful. + */ + public PagedList listByReplicationProtectionContainersNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectableItemInner> object + */ + public Observable> listByReplicationProtectionContainersNextAsync(final String nextPageLink) { + return listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectableItemInner> object + */ + public Observable>> listByReplicationProtectionContainersNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of protectable items. + * Lists the protectable items in a protection container. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectableItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationProtectionContainersNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectionContainersNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemImpl.java new file mode 100644 index 0000000000000..0b0d8c4e1e057 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemImpl.java @@ -0,0 +1,145 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItem; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateReplicationProtectedItemInputProperties; +import java.util.List; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EnableProtectionInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItemProperties; +import rx.functions.Func1; + +class ReplicationProtectedItemImpl extends CreatableUpdatableImpl implements ReplicationProtectedItem, ReplicationProtectedItem.Definition, ReplicationProtectedItem.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private String protectionContainerName; + private String replicatedProtectedItemName; + private EnableProtectionInputProperties cproperties; + private UpdateReplicationProtectedItemInputProperties uproperties; + + ReplicationProtectedItemImpl(String name, RecoveryServicesManager manager) { + super(name, new ReplicationProtectedItemInner()); + this.manager = manager; + // Set resource name + this.replicatedProtectedItemName = name; + // + this.cproperties = new EnableProtectionInputProperties(); + this.uproperties = new UpdateReplicationProtectedItemInputProperties(); + } + + ReplicationProtectedItemImpl(ReplicationProtectedItemInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.replicatedProtectedItemName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.protectionContainerName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectionContainers"); + this.replicatedProtectedItemName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationProtectedItems"); + // + this.cproperties = new EnableProtectionInputProperties(); + this.uproperties = new UpdateReplicationProtectedItemInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationProtectedItemsInner client = this.manager().inner().replicationProtectedItems(); + return client.createAsync(this.fabricName, this.protectionContainerName, this.replicatedProtectedItemName, this.cproperties) + .map(new Func1() { + @Override + public ReplicationProtectedItemInner call(ReplicationProtectedItemInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationProtectedItemsInner client = this.manager().inner().replicationProtectedItems(); + return client.updateAsync(this.fabricName, this.protectionContainerName, this.replicatedProtectedItemName, this.uproperties) + .map(new Func1() { + @Override + public ReplicationProtectedItemInner call(ReplicationProtectedItemInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationProtectedItemsInner client = this.manager().inner().replicationProtectedItems(); + return client.getAsync(this.fabricName, this.protectionContainerName, this.replicatedProtectedItemName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new EnableProtectionInputProperties(); + this.uproperties = new UpdateReplicationProtectedItemInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public ReplicationProtectedItemProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public ReplicationProtectedItemImpl withExistingReplicationProtectionContainer(String fabricName, String protectionContainerName) { + this.fabricName = fabricName; + this.protectionContainerName = protectionContainerName; + return this; + } + + @Override + public ReplicationProtectedItemImpl withProperties(EnableProtectionInputProperties properties) { + this.cproperties = properties; + return this; + } + + @Override + public ReplicationProtectedItemImpl withProperties(UpdateReplicationProtectedItemInputProperties properties) { + this.uproperties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemInner.java new file mode 100644 index 0000000000000..a9cbea5d986c0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItemProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Replication protected item. + */ +public class ReplicationProtectedItemInner extends ProxyResource { + /** + * The custom data. + */ + @JsonProperty(value = "properties") + private ReplicationProtectedItemProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the custom data. + * + * @return the properties value + */ + public ReplicationProtectedItemProperties properties() { + return this.properties; + } + + /** + * Set the custom data. + * + * @param properties the properties value to set + * @return the ReplicationProtectedItemInner object itself. + */ + public ReplicationProtectedItemInner withProperties(ReplicationProtectedItemProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the ReplicationProtectedItemInner object itself. + */ + public ReplicationProtectedItemInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemsImpl.java new file mode 100644 index 0000000000000..3120b5920e806 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemsImpl.java @@ -0,0 +1,214 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItem; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestFailoverCleanupInputProperties; + +class ReplicationProtectedItemsImpl extends WrapperImpl implements ReplicationProtectedItems { + private final RecoveryServicesManager manager; + + ReplicationProtectedItemsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationProtectedItems()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public ReplicationProtectedItemImpl define(String name) { + return wrapModel(name); + } + + private ReplicationProtectedItemImpl wrapModel(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + + private ReplicationProtectedItemImpl wrapModel(String name) { + return new ReplicationProtectedItemImpl(name, this.manager()); + } + + @Override + public Observable applyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.applyRecoveryPointAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable failoverCommitAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.failoverCommitAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable plannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.plannedFailoverAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Completable deleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.deleteAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toCompletable(); + } + + @Override + public Observable repairReplicationAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.repairReplicationAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable reprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.reprotectAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable testFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.testFailoverAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable testFailoverCleanupAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties) { + ReplicationProtectedItemsInner client = this.inner(); + return client.testFailoverCleanupAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable unplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.unplannedFailoverAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable updateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.updateMobilityServiceAsync(fabricName, protectionContainerName, replicationProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable listAsync() { + ReplicationProtectedItemsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return new ReplicationProtectedItemImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.listByReplicationProtectionContainersAsync(fabricName, protectionContainerName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.getAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1() { + @Override + public ReplicationProtectedItem call(ReplicationProtectedItemInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable purgeAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + ReplicationProtectedItemsInner client = this.inner(); + return client.purgeAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemsInner.java new file mode 100644 index 0000000000000..0928578a288ed --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectedItemsInner.java @@ -0,0 +1,5215 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ApplyRecoveryPointInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ApplyRecoveryPointInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.DisableProtectionInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.DisableProtectionInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EnableProtectionInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.EnableProtectionInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.PlannedFailoverInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.PlannedFailoverInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReverseReplicationInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReverseReplicationInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestFailoverCleanupInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestFailoverCleanupInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestFailoverInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TestFailoverInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UnplannedFailoverInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UnplannedFailoverInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateMobilityServiceRequest; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateMobilityServiceRequestProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateReplicationProtectedItemInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateReplicationProtectedItemInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationProtectedItems. + */ +public class ReplicationProtectedItemsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationProtectedItemsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationProtectedItemsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationProtectedItemsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationProtectedItemsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationProtectedItems to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationProtectedItemsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems listByReplicationProtectionContainers" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems") + Observable> listByReplicationProtectionContainers(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body EnableProtectionInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body EnableProtectionInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems purge" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}", method = "DELETE", hasBody = true) + Observable> purge(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginPurge" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}", method = "DELETE", hasBody = true) + Observable> beginPurge(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems update" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}") + Observable> update(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateReplicationProtectedItemInput updateProtectionInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginUpdate" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}") + Observable> beginUpdate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateReplicationProtectedItemInput updateProtectionInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems applyRecoveryPoint" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/applyRecoveryPoint") + Observable> applyRecoveryPoint(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ApplyRecoveryPointInput applyRecoveryPointInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginApplyRecoveryPoint" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/applyRecoveryPoint") + Observable> beginApplyRecoveryPoint(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ApplyRecoveryPointInput applyRecoveryPointInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems failoverCommit" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/failoverCommit") + Observable> failoverCommit(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginFailoverCommit" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/failoverCommit") + Observable> beginFailoverCommit(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems plannedFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/plannedFailover") + Observable> plannedFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body PlannedFailoverInput failoverInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginPlannedFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/plannedFailover") + Observable> beginPlannedFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body PlannedFailoverInput failoverInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems delete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/remove") + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body DisableProtectionInput disableProtectionInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginDelete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/remove") + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body DisableProtectionInput disableProtectionInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems repairReplication" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/repairReplication") + Observable> repairReplication(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginRepairReplication" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/repairReplication") + Observable> beginRepairReplication(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems reprotect" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/reProtect") + Observable> reprotect(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ReverseReplicationInput rrInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginReprotect" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/reProtect") + Observable> beginReprotect(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ReverseReplicationInput rrInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems testFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/testFailover") + Observable> testFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TestFailoverInput failoverInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginTestFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/testFailover") + Observable> beginTestFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TestFailoverInput failoverInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems testFailoverCleanup" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/testFailoverCleanup") + Observable> testFailoverCleanup(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TestFailoverCleanupInput cleanupInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginTestFailoverCleanup" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/testFailoverCleanup") + Observable> beginTestFailoverCleanup(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TestFailoverCleanupInput cleanupInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems unplannedFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/unplannedFailover") + Observable> unplannedFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UnplannedFailoverInput failoverInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginUnplannedFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/unplannedFailover") + Observable> beginUnplannedFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UnplannedFailoverInput failoverInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems updateMobilityService" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicationProtectedItemName}/updateMobilityService") + Observable> updateMobilityService(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicationProtectedItemName") String replicationProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateMobilityServiceRequest updateMobilityServiceRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems beginUpdateMobilityService" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicationProtectedItemName}/updateMobilityService") + Observable> beginUpdateMobilityService(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicationProtectedItemName") String replicationProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateMobilityServiceRequest updateMobilityServiceRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationProtectedItems") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Query("skipToken") String skipToken, @Query("$filter") String filter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems listByReplicationProtectionContainersNext" }) + @GET + Observable> listByReplicationProtectionContainersNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectedItems listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ReplicationProtectedItemInner> object if successful. + */ + public PagedList listByReplicationProtectionContainers(final String fabricName, final String protectionContainerName) { + ServiceResponse> response = listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName) { + return listByReplicationProtectionContainersWithServiceResponseAsync(fabricName, protectionContainerName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable>> listByReplicationProtectionContainersWithServiceResponseAsync(final String fabricName, final String protectionContainerName) { + return listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + ServiceResponse> * @param fabricName Fabric name. + ServiceResponse> * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ReplicationProtectedItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersSinglePageAsync(final String fabricName, final String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationProtectionContainers(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectionContainersDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the details of a Replication protected item. + * Gets the details of an ASR replication protected item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner get(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Gets the details of a Replication protected item. + * Gets the details of an ASR replication protected item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Gets the details of a Replication protected item. + * Gets the details of an ASR replication protected item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable getAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the details of a Replication protected item. + * Gets the details of an ASR replication protected item. + * + * @param fabricName Fabric unique name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner create(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final EnableProtectionInputProperties properties = null; + EnableProtectionInput input = new EnableProtectionInput(); + input.withProperties(null); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param properties Enable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner create(String fabricName, String protectionContainerName, String replicatedProtectedItemName, EnableProtectionInputProperties properties) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param properties Enable protection input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, EnableProtectionInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param properties Enable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, EnableProtectionInputProperties properties) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param properties Enable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, EnableProtectionInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + EnableProtectionInput input = new EnableProtectionInput(); + input.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginCreate(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginCreateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final EnableProtectionInputProperties properties = null; + EnableProtectionInput input = new EnableProtectionInput(); + input.withProperties(null); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param properties Enable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginCreate(String fabricName, String protectionContainerName, String replicatedProtectedItemName, EnableProtectionInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param properties Enable protection input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, EnableProtectionInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param properties Enable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginCreateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, EnableProtectionInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Enables protection. + * The operation to create an ASR replication protected item (Enable replication). + * + * @param fabricName Name of the fabric. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName A name for the replication protected item. + * @param properties Enable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, EnableProtectionInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + EnableProtectionInput input = new EnableProtectionInput(); + input.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void purge(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + purgeWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture purgeAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(purgeWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable purgeAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return purgeWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> purgeWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.purge(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginPurge(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + beginPurgeWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginPurgeAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginPurgeWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginPurgeAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginPurgeWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Purges protection. + * The operation to delete or purge a replication protected item. This operation will force delete the replication protected item. Use the remove operation on replication protected item to perform a clean disable replication for the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginPurgeWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginPurge(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginPurgeDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginPurgeDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner update(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateReplicationProtectedItemInputProperties properties = null; + UpdateReplicationProtectedItemInput updateProtectionInput = new UpdateReplicationProtectedItemInput(); + updateProtectionInput.withProperties(null); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), updateProtectionInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Update replication protected item properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner update(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UpdateReplicationProtectedItemInputProperties properties) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Update replication protected item properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UpdateReplicationProtectedItemInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Update replication protected item properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UpdateReplicationProtectedItemInputProperties properties) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Update replication protected item properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UpdateReplicationProtectedItemInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateReplicationProtectedItemInput updateProtectionInput = new UpdateReplicationProtectedItemInput(); + updateProtectionInput.withProperties(properties); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), updateProtectionInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginUpdate(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginUpdateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateReplicationProtectedItemInputProperties properties = null; + UpdateReplicationProtectedItemInput updateProtectionInput = new UpdateReplicationProtectedItemInput(); + updateProtectionInput.withProperties(null); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), updateProtectionInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Update replication protected item properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginUpdate(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UpdateReplicationProtectedItemInputProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Update replication protected item properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UpdateReplicationProtectedItemInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Update replication protected item properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginUpdateAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UpdateReplicationProtectedItemInputProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates protection. + * The operation to update the recovery settings of an ASR replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Update replication protected item properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UpdateReplicationProtectedItemInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateReplicationProtectedItemInput updateProtectionInput = new UpdateReplicationProtectedItemInput(); + updateProtectionInput.withProperties(properties); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), updateProtectionInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner applyRecoveryPoint(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return applyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture applyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(applyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable applyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return applyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> applyRecoveryPointWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final ApplyRecoveryPointInputProperties properties = null; + ApplyRecoveryPointInput applyRecoveryPointInput = new ApplyRecoveryPointInput(); + applyRecoveryPointInput.withProperties(null); + Observable> observable = service.applyRecoveryPoint(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), applyRecoveryPointInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param properties The input properties to apply recovery point. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner applyRecoveryPoint(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ApplyRecoveryPointInputProperties properties) { + return applyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param properties The input properties to apply recovery point. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture applyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ApplyRecoveryPointInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(applyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param properties The input properties to apply recovery point. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable applyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ApplyRecoveryPointInputProperties properties) { + return applyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param properties The input properties to apply recovery point. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> applyRecoveryPointWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ApplyRecoveryPointInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + ApplyRecoveryPointInput applyRecoveryPointInput = new ApplyRecoveryPointInput(); + applyRecoveryPointInput.withProperties(properties); + Observable> observable = service.applyRecoveryPoint(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), applyRecoveryPointInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginApplyRecoveryPoint(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginApplyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginApplyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginApplyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginApplyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginApplyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginApplyRecoveryPointWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final ApplyRecoveryPointInputProperties properties = null; + ApplyRecoveryPointInput applyRecoveryPointInput = new ApplyRecoveryPointInput(); + applyRecoveryPointInput.withProperties(null); + return service.beginApplyRecoveryPoint(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), applyRecoveryPointInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginApplyRecoveryPointDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param properties The input properties to apply recovery point. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginApplyRecoveryPoint(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ApplyRecoveryPointInputProperties properties) { + return beginApplyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param properties The input properties to apply recovery point. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginApplyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ApplyRecoveryPointInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginApplyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param properties The input properties to apply recovery point. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginApplyRecoveryPointAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ApplyRecoveryPointInputProperties properties) { + return beginApplyRecoveryPointWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Change or apply recovery point. + * The operation to change the recovery point of a failed over replication protected item. + * + * @param fabricName The ARM fabric name. + * @param protectionContainerName The protection container name. + * @param replicatedProtectedItemName The replicated protected item's name. + * @param properties The input properties to apply recovery point. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginApplyRecoveryPointWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ApplyRecoveryPointInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + ApplyRecoveryPointInput applyRecoveryPointInput = new ApplyRecoveryPointInput(); + applyRecoveryPointInput.withProperties(properties); + return service.beginApplyRecoveryPoint(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), applyRecoveryPointInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginApplyRecoveryPointDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginApplyRecoveryPointDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner failoverCommit(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return failoverCommitWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture failoverCommitAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(failoverCommitWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable failoverCommitAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return failoverCommitWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> failoverCommitWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.failoverCommit(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginFailoverCommit(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginFailoverCommitWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginFailoverCommitAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginFailoverCommitWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginFailoverCommitAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginFailoverCommitWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute commit failover. + * Operation to commit the failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginFailoverCommitWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginFailoverCommit(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginFailoverCommitDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginFailoverCommitDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner plannedFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return plannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture plannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(plannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable plannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return plannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> plannedFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final PlannedFailoverInputProperties properties = null; + PlannedFailoverInput failoverInput = new PlannedFailoverInput(); + failoverInput.withProperties(null); + Observable> observable = service.plannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner plannedFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName, PlannedFailoverInputProperties properties) { + return plannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture plannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, PlannedFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(plannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable plannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, PlannedFailoverInputProperties properties) { + return plannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> plannedFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, PlannedFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + PlannedFailoverInput failoverInput = new PlannedFailoverInput(); + failoverInput.withProperties(properties); + Observable> observable = service.plannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginPlannedFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginPlannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginPlannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginPlannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginPlannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginPlannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginPlannedFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final PlannedFailoverInputProperties properties = null; + PlannedFailoverInput failoverInput = new PlannedFailoverInput(); + failoverInput.withProperties(null); + return service.beginPlannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginPlannedFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginPlannedFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName, PlannedFailoverInputProperties properties) { + return beginPlannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginPlannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, PlannedFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginPlannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginPlannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, PlannedFailoverInputProperties properties) { + return beginPlannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute planned failover. + * Operation to initiate a planned failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginPlannedFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, PlannedFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + PlannedFailoverInput failoverInput = new PlannedFailoverInput(); + failoverInput.withProperties(properties); + return service.beginPlannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginPlannedFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginPlannedFailoverDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + deleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return deleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final DisableProtectionInputProperties properties = null; + DisableProtectionInput disableProtectionInput = new DisableProtectionInput(); + disableProtectionInput.withProperties(null); + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), disableProtectionInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Disable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String protectionContainerName, String replicatedProtectedItemName, DisableProtectionInputProperties properties) { + deleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Disable protection input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, DisableProtectionInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Disable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, DisableProtectionInputProperties properties) { + return deleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Disable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, DisableProtectionInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + DisableProtectionInput disableProtectionInput = new DisableProtectionInput(); + disableProtectionInput.withProperties(properties); + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), disableProtectionInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final DisableProtectionInputProperties properties = null; + DisableProtectionInput disableProtectionInput = new DisableProtectionInput(); + disableProtectionInput.withProperties(null); + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), disableProtectionInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Disable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String protectionContainerName, String replicatedProtectedItemName, DisableProtectionInputProperties properties) { + beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Disable protection input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, DisableProtectionInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Disable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, DisableProtectionInputProperties properties) { + return beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Disables protection. + * The operation to disable replication on a replication protected item. This will also remove the item. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Disable protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, DisableProtectionInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + DisableProtectionInput disableProtectionInput = new DisableProtectionInput(); + disableProtectionInput.withProperties(properties); + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), disableProtectionInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner repairReplication(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return repairReplicationWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture repairReplicationAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(repairReplicationWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable repairReplicationAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return repairReplicationWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> repairReplicationWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.repairReplication(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginRepairReplication(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginRepairReplicationWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginRepairReplicationAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginRepairReplicationWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginRepairReplicationAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginRepairReplicationWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Resynchronize or repair replication. + * The operation to start resynchronize/repair replication for a replication protected item requiring resynchronization. + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the container. + * @param replicatedProtectedItemName The name of the replication protected item. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginRepairReplicationWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginRepairReplication(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginRepairReplicationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginRepairReplicationDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner reprotect(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return reprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture reprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(reprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable reprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return reprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> reprotectWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final ReverseReplicationInputProperties properties = null; + ReverseReplicationInput rrInput = new ReverseReplicationInput(); + rrInput.withProperties(null); + Observable> observable = service.reprotect(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), rrInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Reverse replication properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner reprotect(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ReverseReplicationInputProperties properties) { + return reprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Reverse replication properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture reprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ReverseReplicationInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(reprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Reverse replication properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable reprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ReverseReplicationInputProperties properties) { + return reprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Reverse replication properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> reprotectWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ReverseReplicationInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + ReverseReplicationInput rrInput = new ReverseReplicationInput(); + rrInput.withProperties(properties); + Observable> observable = service.reprotect(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), rrInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginReprotect(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginReprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginReprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginReprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginReprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginReprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginReprotectWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final ReverseReplicationInputProperties properties = null; + ReverseReplicationInput rrInput = new ReverseReplicationInput(); + rrInput.withProperties(null); + return service.beginReprotect(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), rrInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginReprotectDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Reverse replication properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginReprotect(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ReverseReplicationInputProperties properties) { + return beginReprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Reverse replication properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginReprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ReverseReplicationInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginReprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Reverse replication properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginReprotectAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ReverseReplicationInputProperties properties) { + return beginReprotectWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute Reverse Replication\Reprotect. + * Operation to reprotect or reverse replicate a failed over replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Reverse replication properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginReprotectWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, ReverseReplicationInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + ReverseReplicationInput rrInput = new ReverseReplicationInput(); + rrInput.withProperties(properties); + return service.beginReprotect(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), rrInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginReprotectDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginReprotectDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner testFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return testFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture testFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(testFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable testFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return testFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> testFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final TestFailoverInputProperties properties = null; + TestFailoverInput failoverInput = new TestFailoverInput(); + failoverInput.withProperties(null); + Observable> observable = service.testFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner testFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverInputProperties properties) { + return testFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture testFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(testFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable testFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverInputProperties properties) { + return testFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> testFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + TestFailoverInput failoverInput = new TestFailoverInput(); + failoverInput.withProperties(properties); + Observable> observable = service.testFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginTestFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginTestFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginTestFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginTestFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginTestFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginTestFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginTestFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final TestFailoverInputProperties properties = null; + TestFailoverInput failoverInput = new TestFailoverInput(); + failoverInput.withProperties(null); + return service.beginTestFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginTestFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginTestFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverInputProperties properties) { + return beginTestFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginTestFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginTestFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginTestFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverInputProperties properties) { + return beginTestFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover. + * Operation to perform a test failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginTestFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + TestFailoverInput failoverInput = new TestFailoverInput(); + failoverInput.withProperties(properties); + return service.beginTestFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginTestFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginTestFailoverDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner testFailoverCleanup(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties) { + return testFailoverCleanupWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture testFailoverCleanupAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(testFailoverCleanupWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable testFailoverCleanupAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties) { + return testFailoverCleanupWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> testFailoverCleanupWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + TestFailoverCleanupInput cleanupInput = new TestFailoverCleanupInput(); + cleanupInput.withProperties(properties); + Observable> observable = service.testFailoverCleanup(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), cleanupInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginTestFailoverCleanup(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties) { + return beginTestFailoverCleanupWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginTestFailoverCleanupAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginTestFailoverCleanupWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginTestFailoverCleanupAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties) { + return beginTestFailoverCleanupWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover cleanup. + * Operation to clean up the test failover of a replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginTestFailoverCleanupWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, TestFailoverCleanupInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + TestFailoverCleanupInput cleanupInput = new TestFailoverCleanupInput(); + cleanupInput.withProperties(properties); + return service.beginTestFailoverCleanup(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), cleanupInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginTestFailoverCleanupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginTestFailoverCleanupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner unplannedFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return unplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().last().body(); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture unplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(unplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable unplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return unplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> unplannedFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UnplannedFailoverInputProperties properties = null; + UnplannedFailoverInput failoverInput = new UnplannedFailoverInput(); + failoverInput.withProperties(null); + Observable> observable = service.unplannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner unplannedFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UnplannedFailoverInputProperties properties) { + return unplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture unplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UnplannedFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(unplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable unplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UnplannedFailoverInputProperties properties) { + return unplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> unplannedFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UnplannedFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UnplannedFailoverInput failoverInput = new UnplannedFailoverInput(); + failoverInput.withProperties(properties); + Observable> observable = service.unplannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginUnplannedFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginUnplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single().body(); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUnplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUnplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName), serviceCallback); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginUnplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + return beginUnplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginUnplannedFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UnplannedFailoverInputProperties properties = null; + UnplannedFailoverInput failoverInput = new UnplannedFailoverInput(); + failoverInput.withProperties(null); + return service.beginUnplannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUnplannedFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginUnplannedFailover(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UnplannedFailoverInputProperties properties) { + return beginUnplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUnplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UnplannedFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUnplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties), serviceCallback); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginUnplannedFailoverAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UnplannedFailoverInputProperties properties) { + return beginUnplannedFailoverWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute unplanned failover. + * Operation to initiate a failover of the replication protected item. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param properties Planned failover input properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginUnplannedFailoverWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicatedProtectedItemName, UnplannedFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UnplannedFailoverInput failoverInput = new UnplannedFailoverInput(); + failoverInput.withProperties(properties); + return service.beginUnplannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), failoverInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUnplannedFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUnplannedFailoverDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner updateMobilityService(String fabricName, String protectionContainerName, String replicationProtectedItemName) { + return updateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName).toBlocking().last().body(); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName), serviceCallback); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName) { + return updateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateMobilityServiceWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicationProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicationProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateMobilityServiceRequestProperties properties = null; + UpdateMobilityServiceRequest updateMobilityServiceRequest = new UpdateMobilityServiceRequest(); + updateMobilityServiceRequest.withProperties(null); + Observable> observable = service.updateMobilityService(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicationProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), updateMobilityServiceRequest, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param properties The properties of the update mobility service request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner updateMobilityService(String fabricName, String protectionContainerName, String replicationProtectedItemName, UpdateMobilityServiceRequestProperties properties) { + return updateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName, properties).toBlocking().last().body(); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param properties The properties of the update mobility service request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName, UpdateMobilityServiceRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName, properties), serviceCallback); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param properties The properties of the update mobility service request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName, UpdateMobilityServiceRequestProperties properties) { + return updateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param properties The properties of the update mobility service request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateMobilityServiceWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName, UpdateMobilityServiceRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicationProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicationProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateMobilityServiceRequest updateMobilityServiceRequest = new UpdateMobilityServiceRequest(); + updateMobilityServiceRequest.withProperties(properties); + Observable> observable = service.updateMobilityService(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicationProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), updateMobilityServiceRequest, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginUpdateMobilityService(String fabricName, String protectionContainerName, String replicationProtectedItemName) { + return beginUpdateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName).toBlocking().single().body(); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName), serviceCallback); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginUpdateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName) { + return beginUpdateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginUpdateMobilityServiceWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicationProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicationProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateMobilityServiceRequestProperties properties = null; + UpdateMobilityServiceRequest updateMobilityServiceRequest = new UpdateMobilityServiceRequest(); + updateMobilityServiceRequest.withProperties(null); + return service.beginUpdateMobilityService(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicationProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), updateMobilityServiceRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateMobilityServiceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param properties The properties of the update mobility service request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationProtectedItemInner object if successful. + */ + public ReplicationProtectedItemInner beginUpdateMobilityService(String fabricName, String protectionContainerName, String replicationProtectedItemName, UpdateMobilityServiceRequestProperties properties) { + return beginUpdateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName, properties).toBlocking().single().body(); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param properties The properties of the update mobility service request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName, UpdateMobilityServiceRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName, properties), serviceCallback); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param properties The properties of the update mobility service request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable beginUpdateMobilityServiceAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName, UpdateMobilityServiceRequestProperties properties) { + return beginUpdateMobilityServiceWithServiceResponseAsync(fabricName, protectionContainerName, replicationProtectedItemName, properties).map(new Func1, ReplicationProtectedItemInner>() { + @Override + public ReplicationProtectedItemInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update the mobility service on a protected item. + * The operation to update(push update) the installed mobility service software on a replication protected item to the latest available version. + * + * @param fabricName The name of the fabric containing the protected item. + * @param protectionContainerName The name of the container containing the protected item. + * @param replicationProtectedItemName The name of the protected item on which the agent is to be updated. + * @param properties The properties of the update mobility service request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ReplicationProtectedItemInner object + */ + public Observable> beginUpdateMobilityServiceWithServiceResponseAsync(String fabricName, String protectionContainerName, String replicationProtectedItemName, UpdateMobilityServiceRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicationProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicationProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateMobilityServiceRequest updateMobilityServiceRequest = new UpdateMobilityServiceRequest(); + updateMobilityServiceRequest.withProperties(properties); + return service.beginUpdateMobilityService(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicationProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), updateMobilityServiceRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateMobilityServiceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateMobilityServiceDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ReplicationProtectedItemInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ReplicationProtectedItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String skipToken = null; + final String filter = null; + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), skipToken, filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param skipToken The pagination token. Possible values: "FabricId" or "FabricId_CloudId" or null + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ReplicationProtectedItemInner> object if successful. + */ + public PagedList list(final String skipToken, final String filter) { + ServiceResponse> response = listSinglePageAsync(skipToken, filter).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param skipToken The pagination token. Possible values: "FabricId" or "FabricId_CloudId" or null + * @param filter OData filter options. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final String skipToken, final String filter, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(skipToken, filter), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param skipToken The pagination token. Possible values: "FabricId" or "FabricId_CloudId" or null + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable> listAsync(final String skipToken, final String filter) { + return listWithServiceResponseAsync(skipToken, filter) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param skipToken The pagination token. Possible values: "FabricId" or "FabricId_CloudId" or null + * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable>> listWithServiceResponseAsync(final String skipToken, final String filter) { + return listSinglePageAsync(skipToken, filter) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + ServiceResponse> * @param skipToken The pagination token. Possible values: "FabricId" or "FabricId_CloudId" or null + ServiceResponse> * @param filter OData filter options. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ReplicationProtectedItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String skipToken, final String filter) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), skipToken, filter, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ReplicationProtectedItemInner> object if successful. + */ + public PagedList listByReplicationProtectionContainersNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable> listByReplicationProtectionContainersNextAsync(final String nextPageLink) { + return listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable>> listByReplicationProtectionContainersNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of Replication protected items. + * Gets the list of ASR replication protected items in the protection container. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ReplicationProtectedItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationProtectionContainersNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectionContainersNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ReplicationProtectedItemInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ReplicationProtectedItemInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of replication protected items. + * Gets the list of ASR replication protected items in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ReplicationProtectedItemInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainerMappingsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainerMappingsImpl.java new file mode 100644 index 0000000000000..011d88db4c38f --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainerMappingsImpl.java @@ -0,0 +1,105 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainerMapping; + +class ReplicationProtectionContainerMappingsImpl extends WrapperImpl implements ReplicationProtectionContainerMappings { + private final RecoveryServicesManager manager; + + ReplicationProtectionContainerMappingsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationProtectionContainerMappings()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public ProtectionContainerMappingImpl define(String name) { + return wrapModel(name); + } + + private ProtectionContainerMappingImpl wrapModel(ProtectionContainerMappingInner inner) { + return new ProtectionContainerMappingImpl(inner, manager()); + } + + private ProtectionContainerMappingImpl wrapModel(String name) { + return new ProtectionContainerMappingImpl(name, this.manager()); + } + + @Override + public Completable deleteAsync(String fabricName, String protectionContainerName, String mappingName) { + ReplicationProtectionContainerMappingsInner client = this.inner(); + return client.deleteAsync(fabricName, protectionContainerName, mappingName).toCompletable(); + } + + @Override + public Observable listAsync() { + ReplicationProtectionContainerMappingsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public ProtectionContainerMapping call(ProtectionContainerMappingInner inner) { + return new ProtectionContainerMappingImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName) { + ReplicationProtectionContainerMappingsInner client = this.inner(); + return client.listByReplicationProtectionContainersAsync(fabricName, protectionContainerName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public ProtectionContainerMapping call(ProtectionContainerMappingInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String protectionContainerName, String mappingName) { + ReplicationProtectionContainerMappingsInner client = this.inner(); + return client.getAsync(fabricName, protectionContainerName, mappingName) + .map(new Func1() { + @Override + public ProtectionContainerMapping call(ProtectionContainerMappingInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable purgeAsync(String fabricName, String protectionContainerName, String mappingName) { + ReplicationProtectionContainerMappingsInner client = this.inner(); + return client.purgeAsync(fabricName, protectionContainerName, mappingName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainerMappingsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainerMappingsInner.java new file mode 100644 index 0000000000000..6173b3eda81d8 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainerMappingsInner.java @@ -0,0 +1,2070 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateProtectionContainerMappingInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateProtectionContainerMappingInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RemoveProtectionContainerMappingInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RemoveProtectionContainerMappingInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateProtectionContainerMappingInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateProtectionContainerMappingInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationProtectionContainerMappings. + */ +public class ReplicationProtectionContainerMappingsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationProtectionContainerMappingsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationProtectionContainerMappingsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationProtectionContainerMappingsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationProtectionContainerMappingsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationProtectionContainerMappings to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationProtectionContainerMappingsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings listByReplicationProtectionContainers" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings") + Observable> listByReplicationProtectionContainers(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateProtectionContainerMappingInput creationInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateProtectionContainerMappingInput creationInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings purge" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}", method = "DELETE", hasBody = true) + Observable> purge(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings beginPurge" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}", method = "DELETE", hasBody = true) + Observable> beginPurge(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings update" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}") + Observable> update(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateProtectionContainerMappingInput updateInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings beginUpdate" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}") + Observable> beginUpdate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateProtectionContainerMappingInput updateInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings delete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}/remove") + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RemoveProtectionContainerMappingInput removalInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings beginDelete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectionContainerMappings/{mappingName}/remove") + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("mappingName") String mappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RemoveProtectionContainerMappingInput removalInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationProtectionContainerMappings") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings listByReplicationProtectionContainersNext" }) + @GET + Observable> listByReplicationProtectionContainersNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainerMappings listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectionContainerMappingInner> object if successful. + */ + public PagedList listByReplicationProtectionContainers(final String fabricName, final String protectionContainerName) { + ServiceResponse> response = listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerMappingInner> object + */ + public Observable> listByReplicationProtectionContainersAsync(final String fabricName, final String protectionContainerName) { + return listByReplicationProtectionContainersWithServiceResponseAsync(fabricName, protectionContainerName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerMappingInner> object + */ + public Observable>> listByReplicationProtectionContainersWithServiceResponseAsync(final String fabricName, final String protectionContainerName) { + return listByReplicationProtectionContainersSinglePageAsync(fabricName, protectionContainerName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + ServiceResponse> * @param fabricName Fabric name. + ServiceResponse> * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectionContainerMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersSinglePageAsync(final String fabricName, final String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationProtectionContainers(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectionContainersDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets a protection container mapping/. + * Gets the details of a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection Container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner get(String fabricName, String protectionContainerName, String mappingName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().single().body(); + } + + /** + * Gets a protection container mapping/. + * Gets the details of a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection Container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Gets a protection container mapping/. + * Gets the details of a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection Container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable getAsync(String fabricName, String protectionContainerName, String mappingName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets a protection container mapping/. + * Gets the details of a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection Container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner create(String fabricName, String protectionContainerName, String mappingName) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().last().body(); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String protectionContainerName, String mappingName) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final CreateProtectionContainerMappingInputProperties properties = null; + CreateProtectionContainerMappingInput creationInput = new CreateProtectionContainerMappingInput(); + creationInput.withProperties(null); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), creationInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner create(String fabricName, String protectionContainerName, String mappingName, CreateProtectionContainerMappingInputProperties properties) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).toBlocking().last().body(); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String protectionContainerName, String mappingName, CreateProtectionContainerMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties), serviceCallback); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String protectionContainerName, String mappingName, CreateProtectionContainerMappingInputProperties properties) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName, CreateProtectionContainerMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + CreateProtectionContainerMappingInput creationInput = new CreateProtectionContainerMappingInput(); + creationInput.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), creationInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner beginCreate(String fabricName, String protectionContainerName, String mappingName) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().single().body(); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable beginCreateAsync(String fabricName, String protectionContainerName, String mappingName) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final CreateProtectionContainerMappingInputProperties properties = null; + CreateProtectionContainerMappingInput creationInput = new CreateProtectionContainerMappingInput(); + creationInput.withProperties(null); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), creationInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner beginCreate(String fabricName, String protectionContainerName, String mappingName, CreateProtectionContainerMappingInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).toBlocking().single().body(); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String protectionContainerName, String mappingName, CreateProtectionContainerMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties), serviceCallback); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable beginCreateAsync(String fabricName, String protectionContainerName, String mappingName, CreateProtectionContainerMappingInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create protection container mapping. + * The operation to create a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName, CreateProtectionContainerMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + CreateProtectionContainerMappingInput creationInput = new CreateProtectionContainerMappingInput(); + creationInput.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), creationInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void purge(String fabricName, String protectionContainerName, String mappingName) { + purgeWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().last().body(); + } + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture purgeAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(purgeWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable purgeAsync(String fabricName, String protectionContainerName, String mappingName) { + return purgeWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> purgeWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.purge(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginPurge(String fabricName, String protectionContainerName, String mappingName) { + beginPurgeWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().single().body(); + } + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginPurgeAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginPurgeWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginPurgeAsync(String fabricName, String protectionContainerName, String mappingName) { + return beginPurgeWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Purge protection container mapping. + * The operation to purge(force delete) a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginPurgeWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginPurge(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginPurgeDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginPurgeDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner update(String fabricName, String protectionContainerName, String mappingName) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().last().body(); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String protectionContainerName, String mappingName) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateProtectionContainerMappingInputProperties properties = null; + UpdateProtectionContainerMappingInput updateInput = new UpdateProtectionContainerMappingInput(); + updateInput.withProperties(null); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), updateInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Update protection container mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner update(String fabricName, String protectionContainerName, String mappingName, UpdateProtectionContainerMappingInputProperties properties) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).toBlocking().last().body(); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Update protection container mapping input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String protectionContainerName, String mappingName, UpdateProtectionContainerMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties), serviceCallback); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Update protection container mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String protectionContainerName, String mappingName, UpdateProtectionContainerMappingInputProperties properties) { + return updateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Update protection container mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName, UpdateProtectionContainerMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateProtectionContainerMappingInput updateInput = new UpdateProtectionContainerMappingInput(); + updateInput.withProperties(properties); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), updateInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner beginUpdate(String fabricName, String protectionContainerName, String mappingName) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().single().body(); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable beginUpdateAsync(String fabricName, String protectionContainerName, String mappingName) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateProtectionContainerMappingInputProperties properties = null; + UpdateProtectionContainerMappingInput updateInput = new UpdateProtectionContainerMappingInput(); + updateInput.withProperties(null); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), updateInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Update protection container mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerMappingInner object if successful. + */ + public ProtectionContainerMappingInner beginUpdate(String fabricName, String protectionContainerName, String mappingName, UpdateProtectionContainerMappingInputProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).toBlocking().single().body(); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Update protection container mapping input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String protectionContainerName, String mappingName, UpdateProtectionContainerMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties), serviceCallback); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Update protection container mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable beginUpdateAsync(String fabricName, String protectionContainerName, String mappingName, UpdateProtectionContainerMappingInputProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).map(new Func1, ProtectionContainerMappingInner>() { + @Override + public ProtectionContainerMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update protection container mapping. + * The operation to update protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Update protection container mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerMappingInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName, UpdateProtectionContainerMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateProtectionContainerMappingInput updateInput = new UpdateProtectionContainerMappingInput(); + updateInput.withProperties(properties); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), updateInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String protectionContainerName, String mappingName) { + deleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().last().body(); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String protectionContainerName, String mappingName) { + return deleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final RemoveProtectionContainerMappingInputProperties properties = null; + RemoveProtectionContainerMappingInput removalInput = new RemoveProtectionContainerMappingInput(); + removalInput.withProperties(null); + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), removalInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String protectionContainerName, String mappingName, RemoveProtectionContainerMappingInputProperties properties) { + deleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).toBlocking().last().body(); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String protectionContainerName, String mappingName, RemoveProtectionContainerMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties), serviceCallback); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String protectionContainerName, String mappingName, RemoveProtectionContainerMappingInputProperties properties) { + return deleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName, RemoveProtectionContainerMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + RemoveProtectionContainerMappingInput removalInput = new RemoveProtectionContainerMappingInput(); + removalInput.withProperties(properties); + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), removalInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String protectionContainerName, String mappingName) { + beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).toBlocking().single().body(); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String protectionContainerName, String mappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName), serviceCallback); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String protectionContainerName, String mappingName) { + return beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final RemoveProtectionContainerMappingInputProperties properties = null; + RemoveProtectionContainerMappingInput removalInput = new RemoveProtectionContainerMappingInput(); + removalInput.withProperties(null); + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), removalInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String protectionContainerName, String mappingName, RemoveProtectionContainerMappingInputProperties properties) { + beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).toBlocking().single().body(); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String protectionContainerName, String mappingName, RemoveProtectionContainerMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties), serviceCallback); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String protectionContainerName, String mappingName, RemoveProtectionContainerMappingInputProperties properties) { + return beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName, mappingName, properties).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Remove protection container mapping. + * The operation to delete or remove a protection container mapping. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param mappingName Protection container mapping name. + * @param properties Configure protection input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String protectionContainerName, String mappingName, RemoveProtectionContainerMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (mappingName == null) { + throw new IllegalArgumentException("Parameter mappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + RemoveProtectionContainerMappingInput removalInput = new RemoveProtectionContainerMappingInput(); + removalInput.withProperties(properties); + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, mappingName, this.client.apiVersion(), this.client.acceptLanguage(), removalInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectionContainerMappingInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerMappingInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerMappingInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectionContainerMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectionContainerMappingInner> object if successful. + */ + public PagedList listByReplicationProtectionContainersNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectionContainersNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerMappingInner> object + */ + public Observable> listByReplicationProtectionContainersNextAsync(final String nextPageLink) { + return listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerMappingInner> object + */ + public Observable>> listByReplicationProtectionContainersNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationProtectionContainersNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectionContainersNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of protection container mappings for a protection container. + * Lists the protection container mappings for a protection container. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectionContainerMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectionContainersNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationProtectionContainersNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectionContainersNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectionContainersNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectionContainerMappingInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerMappingInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerMappingInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of all protection container mappings in a vault. + * Lists the protection container mappings in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectionContainerMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainersImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainersImpl.java new file mode 100644 index 0000000000000..93fca6e6d22e1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainersImpl.java @@ -0,0 +1,123 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import rx.Completable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ProtectionContainer; + +class ReplicationProtectionContainersImpl extends WrapperImpl implements ReplicationProtectionContainers { + private final RecoveryServicesManager manager; + + ReplicationProtectionContainersImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationProtectionContainers()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public ProtectionContainerImpl define(String name) { + return wrapModel(name); + } + + private ProtectionContainerImpl wrapModel(ProtectionContainerInner inner) { + return new ProtectionContainerImpl(inner, manager()); + } + + private ProtectionContainerImpl wrapModel(String name) { + return new ProtectionContainerImpl(name, this.manager()); + } + + @Override + public Observable discoverProtectableItemAsync(String fabricName, String protectionContainerName) { + ReplicationProtectionContainersInner client = this.inner(); + return client.discoverProtectableItemAsync(fabricName, protectionContainerName) + .map(new Func1() { + @Override + public ProtectionContainer call(ProtectionContainerInner inner) { + return new ProtectionContainerImpl(inner, manager()); + } + }); + } + + @Override + public Completable deleteAsync(String fabricName, String protectionContainerName) { + ReplicationProtectionContainersInner client = this.inner(); + return client.deleteAsync(fabricName, protectionContainerName).toCompletable(); + } + + @Override + public Observable switchProtectionAsync(String fabricName, String protectionContainerName) { + ReplicationProtectionContainersInner client = this.inner(); + return client.switchProtectionAsync(fabricName, protectionContainerName) + .map(new Func1() { + @Override + public ProtectionContainer call(ProtectionContainerInner inner) { + return new ProtectionContainerImpl(inner, manager()); + } + }); + } + + @Override + public Observable listAsync() { + ReplicationProtectionContainersInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public ProtectionContainer call(ProtectionContainerInner inner) { + return new ProtectionContainerImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationFabricsAsync(final String fabricName) { + ReplicationProtectionContainersInner client = this.inner(); + return client.listByReplicationFabricsAsync(fabricName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public ProtectionContainer call(ProtectionContainerInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String protectionContainerName) { + ReplicationProtectionContainersInner client = this.inner(); + return client.getAsync(fabricName, protectionContainerName) + .map(new Func1() { + @Override + public ProtectionContainer call(ProtectionContainerInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainersInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainersInner.java new file mode 100644 index 0000000000000..366b926ee6507 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationProtectionContainersInner.java @@ -0,0 +1,1960 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.collection.InnerSupportsDelete; +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateProtectionContainerInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateProtectionContainerInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.DiscoverProtectableItemRequest; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.DiscoverProtectableItemRequestProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.SwitchProtectionInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.SwitchProtectionInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationProtectionContainers. + */ +public class ReplicationProtectionContainersInner implements InnerSupportsDelete { + /** The Retrofit service to perform REST calls. */ + private ReplicationProtectionContainersService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationProtectionContainersInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationProtectionContainersInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationProtectionContainersService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationProtectionContainers to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationProtectionContainersService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers listByReplicationFabrics" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers") + Observable> listByReplicationFabrics(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateProtectionContainerInput creationInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateProtectionContainerInput creationInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers discoverProtectableItem" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/discoverProtectableItem") + Observable> discoverProtectableItem(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body DiscoverProtectableItemRequest discoverProtectableItemRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers beginDiscoverProtectableItem" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/discoverProtectableItem") + Observable> beginDiscoverProtectableItem(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body DiscoverProtectableItemRequest discoverProtectableItemRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers delete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/remove") + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers beginDelete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/remove") + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers switchProtection" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/switchprotection") + Observable> switchProtection(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SwitchProtectionInput switchInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers beginSwitchProtection" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/switchprotection") + Observable> beginSwitchProtection(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SwitchProtectionInput switchInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationProtectionContainers") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers listByReplicationFabricsNext" }) + @GET + Observable> listByReplicationFabricsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationProtectionContainers listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectionContainerInner> object if successful. + */ + public PagedList listByReplicationFabrics(final String fabricName) { + ServiceResponse> response = listByReplicationFabricsSinglePageAsync(fabricName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param fabricName Fabric name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsAsync(final String fabricName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsSinglePageAsync(fabricName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerInner> object + */ + public Observable> listByReplicationFabricsAsync(final String fabricName) { + return listByReplicationFabricsWithServiceResponseAsync(fabricName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerInner> object + */ + public Observable>> listByReplicationFabricsWithServiceResponseAsync(final String fabricName) { + return listByReplicationFabricsSinglePageAsync(fabricName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + ServiceResponse> * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectionContainerInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsSinglePageAsync(final String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationFabrics(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the protection container details. + * Gets the details of a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner get(String fabricName, String protectionContainerName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().single().body(); + } + + /** + * Gets the protection container details. + * Gets the details of a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Gets the protection container details. + * Gets the details of a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable getAsync(String fabricName, String protectionContainerName) { + return getWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the protection container details. + * Gets the details of a protection container. + * + * @param fabricName Fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner create(String fabricName, String protectionContainerName) { + return createWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().last().body(); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String protectionContainerName) { + return createWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final CreateProtectionContainerInputProperties properties = null; + CreateProtectionContainerInput creationInput = new CreateProtectionContainerInput(); + creationInput.withProperties(null); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), creationInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param properties Create protection container input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner create(String fabricName, String protectionContainerName, CreateProtectionContainerInputProperties properties) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, properties).toBlocking().last().body(); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param properties Create protection container input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String protectionContainerName, CreateProtectionContainerInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, protectionContainerName, properties), serviceCallback); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param properties Create protection container input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String protectionContainerName, CreateProtectionContainerInputProperties properties) { + return createWithServiceResponseAsync(fabricName, protectionContainerName, properties).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param properties Create protection container input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String protectionContainerName, CreateProtectionContainerInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + CreateProtectionContainerInput creationInput = new CreateProtectionContainerInput(); + creationInput.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), creationInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner beginCreate(String fabricName, String protectionContainerName) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().single().body(); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable beginCreateAsync(String fabricName, String protectionContainerName) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final CreateProtectionContainerInputProperties properties = null; + CreateProtectionContainerInput creationInput = new CreateProtectionContainerInput(); + creationInput.withProperties(null); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), creationInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param properties Create protection container input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner beginCreate(String fabricName, String protectionContainerName, CreateProtectionContainerInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, properties).toBlocking().single().body(); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param properties Create protection container input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String protectionContainerName, CreateProtectionContainerInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, properties), serviceCallback); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param properties Create protection container input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable beginCreateAsync(String fabricName, String protectionContainerName, CreateProtectionContainerInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, protectionContainerName, properties).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create a protection container. + * Operation to create a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param properties Create protection container input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String protectionContainerName, CreateProtectionContainerInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + CreateProtectionContainerInput creationInput = new CreateProtectionContainerInput(); + creationInput.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), creationInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner discoverProtectableItem(String fabricName, String protectionContainerName) { + return discoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().last().body(); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture discoverProtectableItemAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(discoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable discoverProtectableItemAsync(String fabricName, String protectionContainerName) { + return discoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> discoverProtectableItemWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final DiscoverProtectableItemRequestProperties properties = null; + DiscoverProtectableItemRequest discoverProtectableItemRequest = new DiscoverProtectableItemRequest(); + discoverProtectableItemRequest.withProperties(null); + Observable> observable = service.discoverProtectableItem(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), discoverProtectableItemRequest, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param properties The properties of a discover protectable item request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner discoverProtectableItem(String fabricName, String protectionContainerName, DiscoverProtectableItemRequestProperties properties) { + return discoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName, properties).toBlocking().last().body(); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param properties The properties of a discover protectable item request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture discoverProtectableItemAsync(String fabricName, String protectionContainerName, DiscoverProtectableItemRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(discoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName, properties), serviceCallback); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param properties The properties of a discover protectable item request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable discoverProtectableItemAsync(String fabricName, String protectionContainerName, DiscoverProtectableItemRequestProperties properties) { + return discoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName, properties).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param properties The properties of a discover protectable item request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> discoverProtectableItemWithServiceResponseAsync(String fabricName, String protectionContainerName, DiscoverProtectableItemRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + DiscoverProtectableItemRequest discoverProtectableItemRequest = new DiscoverProtectableItemRequest(); + discoverProtectableItemRequest.withProperties(properties); + Observable> observable = service.discoverProtectableItem(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), discoverProtectableItemRequest, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner beginDiscoverProtectableItem(String fabricName, String protectionContainerName) { + return beginDiscoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().single().body(); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDiscoverProtectableItemAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDiscoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable beginDiscoverProtectableItemAsync(String fabricName, String protectionContainerName) { + return beginDiscoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable> beginDiscoverProtectableItemWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final DiscoverProtectableItemRequestProperties properties = null; + DiscoverProtectableItemRequest discoverProtectableItemRequest = new DiscoverProtectableItemRequest(); + discoverProtectableItemRequest.withProperties(null); + return service.beginDiscoverProtectableItem(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), discoverProtectableItemRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDiscoverProtectableItemDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param properties The properties of a discover protectable item request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner beginDiscoverProtectableItem(String fabricName, String protectionContainerName, DiscoverProtectableItemRequestProperties properties) { + return beginDiscoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName, properties).toBlocking().single().body(); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param properties The properties of a discover protectable item request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDiscoverProtectableItemAsync(String fabricName, String protectionContainerName, DiscoverProtectableItemRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDiscoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName, properties), serviceCallback); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param properties The properties of a discover protectable item request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable beginDiscoverProtectableItemAsync(String fabricName, String protectionContainerName, DiscoverProtectableItemRequestProperties properties) { + return beginDiscoverProtectableItemWithServiceResponseAsync(fabricName, protectionContainerName, properties).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Adds a protectable item to the replication protection container. + * The operation to a add a protectable item to a protection container(Add physical server.). + * + * @param fabricName The name of the fabric. + * @param protectionContainerName The name of the protection container. + * @param properties The properties of a discover protectable item request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable> beginDiscoverProtectableItemWithServiceResponseAsync(String fabricName, String protectionContainerName, DiscoverProtectableItemRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + DiscoverProtectableItemRequest discoverProtectableItemRequest = new DiscoverProtectableItemRequest(); + discoverProtectableItemRequest.withProperties(properties); + return service.beginDiscoverProtectableItem(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), discoverProtectableItemRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDiscoverProtectableItemDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDiscoverProtectableItemDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String protectionContainerName) { + deleteWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().last().body(); + } + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String protectionContainerName) { + return deleteWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String protectionContainerName) { + beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().single().body(); + } + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String protectionContainerName) { + return beginDeleteWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Removes a protection container. + * Operation to remove a protection container. + * + * @param fabricName Unique fabric ARM name. + * @param protectionContainerName Unique protection container ARM name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner switchProtection(String fabricName, String protectionContainerName) { + return switchProtectionWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().last().body(); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture switchProtectionAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(switchProtectionWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable switchProtectionAsync(String fabricName, String protectionContainerName) { + return switchProtectionWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> switchProtectionWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final SwitchProtectionInputProperties properties = null; + SwitchProtectionInput switchInput = new SwitchProtectionInput(); + switchInput.withProperties(null); + Observable> observable = service.switchProtection(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), switchInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param properties Switch protection properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner switchProtection(String fabricName, String protectionContainerName, SwitchProtectionInputProperties properties) { + return switchProtectionWithServiceResponseAsync(fabricName, protectionContainerName, properties).toBlocking().last().body(); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param properties Switch protection properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture switchProtectionAsync(String fabricName, String protectionContainerName, SwitchProtectionInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(switchProtectionWithServiceResponseAsync(fabricName, protectionContainerName, properties), serviceCallback); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param properties Switch protection properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable switchProtectionAsync(String fabricName, String protectionContainerName, SwitchProtectionInputProperties properties) { + return switchProtectionWithServiceResponseAsync(fabricName, protectionContainerName, properties).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param properties Switch protection properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> switchProtectionWithServiceResponseAsync(String fabricName, String protectionContainerName, SwitchProtectionInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + SwitchProtectionInput switchInput = new SwitchProtectionInput(); + switchInput.withProperties(properties); + Observable> observable = service.switchProtection(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), switchInput, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner beginSwitchProtection(String fabricName, String protectionContainerName) { + return beginSwitchProtectionWithServiceResponseAsync(fabricName, protectionContainerName).toBlocking().single().body(); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginSwitchProtectionAsync(String fabricName, String protectionContainerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginSwitchProtectionWithServiceResponseAsync(fabricName, protectionContainerName), serviceCallback); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable beginSwitchProtectionAsync(String fabricName, String protectionContainerName) { + return beginSwitchProtectionWithServiceResponseAsync(fabricName, protectionContainerName).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable> beginSwitchProtectionWithServiceResponseAsync(String fabricName, String protectionContainerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final SwitchProtectionInputProperties properties = null; + SwitchProtectionInput switchInput = new SwitchProtectionInput(); + switchInput.withProperties(null); + return service.beginSwitchProtection(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), switchInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginSwitchProtectionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param properties Switch protection properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ProtectionContainerInner object if successful. + */ + public ProtectionContainerInner beginSwitchProtection(String fabricName, String protectionContainerName, SwitchProtectionInputProperties properties) { + return beginSwitchProtectionWithServiceResponseAsync(fabricName, protectionContainerName, properties).toBlocking().single().body(); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param properties Switch protection properties + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginSwitchProtectionAsync(String fabricName, String protectionContainerName, SwitchProtectionInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginSwitchProtectionWithServiceResponseAsync(fabricName, protectionContainerName, properties), serviceCallback); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param properties Switch protection properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable beginSwitchProtectionAsync(String fabricName, String protectionContainerName, SwitchProtectionInputProperties properties) { + return beginSwitchProtectionWithServiceResponseAsync(fabricName, protectionContainerName, properties).map(new Func1, ProtectionContainerInner>() { + @Override + public ProtectionContainerInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Switches protection from one container to another or one replication provider to another. + * Operation to switch protection from one container to another or one replication provider to another. + * + * @param fabricName Unique fabric name. + * @param protectionContainerName Protection container name. + * @param properties Switch protection properties + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ProtectionContainerInner object + */ + public Observable> beginSwitchProtectionWithServiceResponseAsync(String fabricName, String protectionContainerName, SwitchProtectionInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + SwitchProtectionInput switchInput = new SwitchProtectionInput(); + switchInput.withProperties(properties); + return service.beginSwitchProtection(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, this.client.apiVersion(), this.client.acceptLanguage(), switchInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginSwitchProtectionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginSwitchProtectionDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectionContainerInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectionContainerInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectionContainerInner> object if successful. + */ + public PagedList listByReplicationFabricsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerInner> object + */ + public Observable> listByReplicationFabricsNextAsync(final String nextPageLink) { + return listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerInner> object + */ + public Observable>> listByReplicationFabricsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of protection container for a fabric. + * Lists the protection containers in the specified fabric. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectionContainerInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationFabricsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<ProtectionContainerInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<ProtectionContainerInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of all protection containers in a vault. + * Lists the protection containers in a vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<ProtectionContainerInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryPlansImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryPlansImpl.java new file mode 100644 index 0000000000000..44ee8d8e6c6c6 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryPlansImpl.java @@ -0,0 +1,157 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlan; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanPlannedFailoverInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanTestFailoverInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanTestFailoverCleanupInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanUnplannedFailoverInputProperties; + +class ReplicationRecoveryPlansImpl extends WrapperImpl implements ReplicationRecoveryPlans { + private final RecoveryServicesManager manager; + + ReplicationRecoveryPlansImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationRecoveryPlans()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public RecoveryPlanImpl define(String name) { + return wrapModel(name); + } + + private RecoveryPlanImpl wrapModel(RecoveryPlanInner inner) { + return new RecoveryPlanImpl(inner, manager()); + } + + private RecoveryPlanImpl wrapModel(String name) { + return new RecoveryPlanImpl(name, this.manager()); + } + + @Override + public Observable failoverCommitAsync(String recoveryPlanName) { + ReplicationRecoveryPlansInner client = this.inner(); + return client.failoverCommitAsync(recoveryPlanName) + .map(new Func1() { + @Override + public RecoveryPlan call(RecoveryPlanInner inner) { + return new RecoveryPlanImpl(inner, manager()); + } + }); + } + + @Override + public Observable plannedFailoverAsync(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties) { + ReplicationRecoveryPlansInner client = this.inner(); + return client.plannedFailoverAsync(recoveryPlanName, properties) + .map(new Func1() { + @Override + public RecoveryPlan call(RecoveryPlanInner inner) { + return new RecoveryPlanImpl(inner, manager()); + } + }); + } + + @Override + public Observable reprotectAsync(String recoveryPlanName) { + ReplicationRecoveryPlansInner client = this.inner(); + return client.reprotectAsync(recoveryPlanName) + .map(new Func1() { + @Override + public RecoveryPlan call(RecoveryPlanInner inner) { + return new RecoveryPlanImpl(inner, manager()); + } + }); + } + + @Override + public Observable testFailoverAsync(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties) { + ReplicationRecoveryPlansInner client = this.inner(); + return client.testFailoverAsync(recoveryPlanName, properties) + .map(new Func1() { + @Override + public RecoveryPlan call(RecoveryPlanInner inner) { + return new RecoveryPlanImpl(inner, manager()); + } + }); + } + + @Override + public Observable testFailoverCleanupAsync(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties) { + ReplicationRecoveryPlansInner client = this.inner(); + return client.testFailoverCleanupAsync(recoveryPlanName, properties) + .map(new Func1() { + @Override + public RecoveryPlan call(RecoveryPlanInner inner) { + return new RecoveryPlanImpl(inner, manager()); + } + }); + } + + @Override + public Observable unplannedFailoverAsync(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties) { + ReplicationRecoveryPlansInner client = this.inner(); + return client.unplannedFailoverAsync(recoveryPlanName, properties) + .map(new Func1() { + @Override + public RecoveryPlan call(RecoveryPlanInner inner) { + return new RecoveryPlanImpl(inner, manager()); + } + }); + } + + @Override + public Observable listAsync() { + ReplicationRecoveryPlansInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public RecoveryPlan call(RecoveryPlanInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String recoveryPlanName) { + ReplicationRecoveryPlansInner client = this.inner(); + return client.getAsync(recoveryPlanName) + .map(new Func1() { + @Override + public RecoveryPlan call(RecoveryPlanInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable deleteAsync(String recoveryPlanName) { + ReplicationRecoveryPlansInner client = this.inner(); + return client.deleteAsync(recoveryPlanName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryPlansInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryPlansInner.java new file mode 100644 index 0000000000000..72515aa4b7f0c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryPlansInner.java @@ -0,0 +1,2216 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateRecoveryPlanInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.CreateRecoveryPlanInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanPlannedFailoverInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanPlannedFailoverInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanTestFailoverCleanupInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanTestFailoverCleanupInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanTestFailoverInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanTestFailoverInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanUnplannedFailoverInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryPlanUnplannedFailoverInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateRecoveryPlanInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateRecoveryPlanInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationRecoveryPlans. + */ +public class ReplicationRecoveryPlansInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationRecoveryPlansService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationRecoveryPlansInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationRecoveryPlansInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationRecoveryPlansService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationRecoveryPlans to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationRecoveryPlansService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateRecoveryPlanInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CreateRecoveryPlanInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans delete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginDelete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans update" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}") + Observable> update(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateRecoveryPlanInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginUpdate" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}") + Observable> beginUpdate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateRecoveryPlanInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans failoverCommit" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/failoverCommit") + Observable> failoverCommit(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginFailoverCommit" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/failoverCommit") + Observable> beginFailoverCommit(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans plannedFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/plannedFailover") + Observable> plannedFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RecoveryPlanPlannedFailoverInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginPlannedFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/plannedFailover") + Observable> beginPlannedFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RecoveryPlanPlannedFailoverInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans reprotect" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/reProtect") + Observable> reprotect(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginReprotect" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/reProtect") + Observable> beginReprotect(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans testFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/testFailover") + Observable> testFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RecoveryPlanTestFailoverInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginTestFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/testFailover") + Observable> beginTestFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RecoveryPlanTestFailoverInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans testFailoverCleanup" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/testFailoverCleanup") + Observable> testFailoverCleanup(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RecoveryPlanTestFailoverCleanupInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginTestFailoverCleanup" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/testFailoverCleanup") + Observable> beginTestFailoverCleanup(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RecoveryPlanTestFailoverCleanupInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans unplannedFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/unplannedFailover") + Observable> unplannedFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RecoveryPlanUnplannedFailoverInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans beginUnplannedFailover" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryPlans/{recoveryPlanName}/unplannedFailover") + Observable> beginUnplannedFailover(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("recoveryPlanName") String recoveryPlanName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body RecoveryPlanUnplannedFailoverInput input, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryPlans listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<RecoveryPlanInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryPlanInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryPlanInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RecoveryPlanInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the requested recovery plan. + * Gets the details of the recovery plan. + * + * @param recoveryPlanName Name of the recovery plan. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner get(String recoveryPlanName) { + return getWithServiceResponseAsync(recoveryPlanName).toBlocking().single().body(); + } + + /** + * Gets the requested recovery plan. + * Gets the details of the recovery plan. + * + * @param recoveryPlanName Name of the recovery plan. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Gets the requested recovery plan. + * Gets the details of the recovery plan. + * + * @param recoveryPlanName Name of the recovery plan. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable getAsync(String recoveryPlanName) { + return getWithServiceResponseAsync(recoveryPlanName).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the requested recovery plan. + * Gets the details of the recovery plan. + * + * @param recoveryPlanName Name of the recovery plan. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> getWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Creates a recovery plan with the given details. + * The operation to create a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner create(String recoveryPlanName, CreateRecoveryPlanInputProperties properties) { + return createWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().last().body(); + } + + /** + * Creates a recovery plan with the given details. + * The operation to create a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan creation properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String recoveryPlanName, CreateRecoveryPlanInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Creates a recovery plan with the given details. + * The operation to create a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String recoveryPlanName, CreateRecoveryPlanInputProperties properties) { + return createWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates a recovery plan with the given details. + * The operation to create a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String recoveryPlanName, CreateRecoveryPlanInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + CreateRecoveryPlanInput input = new CreateRecoveryPlanInput(); + input.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Creates a recovery plan with the given details. + * The operation to create a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginCreate(String recoveryPlanName, CreateRecoveryPlanInputProperties properties) { + return beginCreateWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().single().body(); + } + + /** + * Creates a recovery plan with the given details. + * The operation to create a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan creation properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String recoveryPlanName, CreateRecoveryPlanInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Creates a recovery plan with the given details. + * The operation to create a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginCreateAsync(String recoveryPlanName, CreateRecoveryPlanInputProperties properties) { + return beginCreateWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates a recovery plan with the given details. + * The operation to create a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan creation properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String recoveryPlanName, CreateRecoveryPlanInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + CreateRecoveryPlanInput input = new CreateRecoveryPlanInput(); + input.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String recoveryPlanName) { + deleteWithServiceResponseAsync(recoveryPlanName).toBlocking().last().body(); + } + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String recoveryPlanName) { + return deleteWithServiceResponseAsync(recoveryPlanName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String recoveryPlanName) { + beginDeleteWithServiceResponseAsync(recoveryPlanName).toBlocking().single().body(); + } + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String recoveryPlanName) { + return beginDeleteWithServiceResponseAsync(recoveryPlanName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes the specified recovery plan. + * Delete a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner update(String recoveryPlanName) { + return updateWithServiceResponseAsync(recoveryPlanName).toBlocking().last().body(); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String recoveryPlanName) { + return updateWithServiceResponseAsync(recoveryPlanName).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateRecoveryPlanInputProperties properties = null; + UpdateRecoveryPlanInput input = new UpdateRecoveryPlanInput(); + input.withProperties(null); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan update properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner update(String recoveryPlanName, UpdateRecoveryPlanInputProperties properties) { + return updateWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().last().body(); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan update properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String recoveryPlanName, UpdateRecoveryPlanInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan update properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String recoveryPlanName, UpdateRecoveryPlanInputProperties properties) { + return updateWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan update properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String recoveryPlanName, UpdateRecoveryPlanInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateRecoveryPlanInput input = new UpdateRecoveryPlanInput(); + input.withProperties(properties); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginUpdate(String recoveryPlanName) { + return beginUpdateWithServiceResponseAsync(recoveryPlanName).toBlocking().single().body(); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginUpdateAsync(String recoveryPlanName) { + return beginUpdateWithServiceResponseAsync(recoveryPlanName).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateRecoveryPlanInputProperties properties = null; + UpdateRecoveryPlanInput input = new UpdateRecoveryPlanInput(); + input.withProperties(null); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan update properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginUpdate(String recoveryPlanName, UpdateRecoveryPlanInputProperties properties) { + return beginUpdateWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().single().body(); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan update properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String recoveryPlanName, UpdateRecoveryPlanInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan update properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginUpdateAsync(String recoveryPlanName, UpdateRecoveryPlanInputProperties properties) { + return beginUpdateWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Updates the given recovery plan. + * The operation to update a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties Recovery plan update properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String recoveryPlanName, UpdateRecoveryPlanInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateRecoveryPlanInput input = new UpdateRecoveryPlanInput(); + input.withProperties(properties); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner failoverCommit(String recoveryPlanName) { + return failoverCommitWithServiceResponseAsync(recoveryPlanName).toBlocking().last().body(); + } + + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture failoverCommitAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(failoverCommitWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable failoverCommitAsync(String recoveryPlanName) { + return failoverCommitWithServiceResponseAsync(recoveryPlanName).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> failoverCommitWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.failoverCommit(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginFailoverCommit(String recoveryPlanName) { + return beginFailoverCommitWithServiceResponseAsync(recoveryPlanName).toBlocking().single().body(); + } + + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginFailoverCommitAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginFailoverCommitWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginFailoverCommitAsync(String recoveryPlanName) { + return beginFailoverCommitWithServiceResponseAsync(recoveryPlanName).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute commit failover of the recovery plan. + * The operation to commit the fail over of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginFailoverCommitWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginFailoverCommit(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginFailoverCommitDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginFailoverCommitDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner plannedFailover(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties) { + return plannedFailoverWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().last().body(); + } + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture plannedFailoverAsync(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(plannedFailoverWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable plannedFailoverAsync(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties) { + return plannedFailoverWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> plannedFailoverWithServiceResponseAsync(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + RecoveryPlanPlannedFailoverInput input = new RecoveryPlanPlannedFailoverInput(); + input.withProperties(properties); + Observable> observable = service.plannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginPlannedFailover(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties) { + return beginPlannedFailoverWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().single().body(); + } + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginPlannedFailoverAsync(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginPlannedFailoverWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginPlannedFailoverAsync(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties) { + return beginPlannedFailoverWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute planned failover of the recovery plan. + * The operation to start the planned failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan planned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginPlannedFailoverWithServiceResponseAsync(String recoveryPlanName, RecoveryPlanPlannedFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + RecoveryPlanPlannedFailoverInput input = new RecoveryPlanPlannedFailoverInput(); + input.withProperties(properties); + return service.beginPlannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginPlannedFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginPlannedFailoverDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner reprotect(String recoveryPlanName) { + return reprotectWithServiceResponseAsync(recoveryPlanName).toBlocking().last().body(); + } + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture reprotectAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(reprotectWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable reprotectAsync(String recoveryPlanName) { + return reprotectWithServiceResponseAsync(recoveryPlanName).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> reprotectWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.reprotect(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginReprotect(String recoveryPlanName) { + return beginReprotectWithServiceResponseAsync(recoveryPlanName).toBlocking().single().body(); + } + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginReprotectAsync(String recoveryPlanName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginReprotectWithServiceResponseAsync(recoveryPlanName), serviceCallback); + } + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginReprotectAsync(String recoveryPlanName) { + return beginReprotectWithServiceResponseAsync(recoveryPlanName).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute reprotect of the recovery plan. + * The operation to reprotect(reverse replicate) a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginReprotectWithServiceResponseAsync(String recoveryPlanName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginReprotect(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginReprotectDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginReprotectDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner testFailover(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties) { + return testFailoverWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().last().body(); + } + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture testFailoverAsync(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(testFailoverWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable testFailoverAsync(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties) { + return testFailoverWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> testFailoverWithServiceResponseAsync(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + RecoveryPlanTestFailoverInput input = new RecoveryPlanTestFailoverInput(); + input.withProperties(properties); + Observable> observable = service.testFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginTestFailover(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties) { + return beginTestFailoverWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().single().body(); + } + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginTestFailoverAsync(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginTestFailoverWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginTestFailoverAsync(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties) { + return beginTestFailoverWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover of the recovery plan. + * The operation to start the test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginTestFailoverWithServiceResponseAsync(String recoveryPlanName, RecoveryPlanTestFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + RecoveryPlanTestFailoverInput input = new RecoveryPlanTestFailoverInput(); + input.withProperties(properties); + return service.beginTestFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginTestFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginTestFailoverDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner testFailoverCleanup(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties) { + return testFailoverCleanupWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().last().body(); + } + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture testFailoverCleanupAsync(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(testFailoverCleanupWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable testFailoverCleanupAsync(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties) { + return testFailoverCleanupWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> testFailoverCleanupWithServiceResponseAsync(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + RecoveryPlanTestFailoverCleanupInput input = new RecoveryPlanTestFailoverCleanupInput(); + input.withProperties(properties); + Observable> observable = service.testFailoverCleanup(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginTestFailoverCleanup(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties) { + return beginTestFailoverCleanupWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().single().body(); + } + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginTestFailoverCleanupAsync(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginTestFailoverCleanupWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginTestFailoverCleanupAsync(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties) { + return beginTestFailoverCleanupWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute test failover cleanup of the recovery plan. + * The operation to cleanup test failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan test failover cleanup input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginTestFailoverCleanupWithServiceResponseAsync(String recoveryPlanName, RecoveryPlanTestFailoverCleanupInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + RecoveryPlanTestFailoverCleanupInput input = new RecoveryPlanTestFailoverCleanupInput(); + input.withProperties(properties); + return service.beginTestFailoverCleanup(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginTestFailoverCleanupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginTestFailoverCleanupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner unplannedFailover(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties) { + return unplannedFailoverWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().last().body(); + } + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture unplannedFailoverAsync(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(unplannedFailoverWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable unplannedFailoverAsync(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties) { + return unplannedFailoverWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> unplannedFailoverWithServiceResponseAsync(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + RecoveryPlanUnplannedFailoverInput input = new RecoveryPlanUnplannedFailoverInput(); + input.withProperties(properties); + Observable> observable = service.unplannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryPlanInner object if successful. + */ + public RecoveryPlanInner beginUnplannedFailover(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties) { + return beginUnplannedFailoverWithServiceResponseAsync(recoveryPlanName, properties).toBlocking().single().body(); + } + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUnplannedFailoverAsync(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUnplannedFailoverWithServiceResponseAsync(recoveryPlanName, properties), serviceCallback); + } + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable beginUnplannedFailoverAsync(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties) { + return beginUnplannedFailoverWithServiceResponseAsync(recoveryPlanName, properties).map(new Func1, RecoveryPlanInner>() { + @Override + public RecoveryPlanInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Execute unplanned failover of the recovery plan. + * The operation to start the failover of a recovery plan. + * + * @param recoveryPlanName Recovery plan name. + * @param properties The recovery plan unplanned failover input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryPlanInner object + */ + public Observable> beginUnplannedFailoverWithServiceResponseAsync(String recoveryPlanName, RecoveryPlanUnplannedFailoverInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (recoveryPlanName == null) { + throw new IllegalArgumentException("Parameter recoveryPlanName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + RecoveryPlanUnplannedFailoverInput input = new RecoveryPlanUnplannedFailoverInput(); + input.withProperties(properties); + return service.beginUnplannedFailover(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), recoveryPlanName, this.client.apiVersion(), this.client.acceptLanguage(), input, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUnplannedFailoverDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUnplannedFailoverDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<RecoveryPlanInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryPlanInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryPlanInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of recovery plans. + * Lists the recovery plans in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RecoveryPlanInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryServicesProvidersImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryServicesProvidersImpl.java new file mode 100644 index 0000000000000..46908098e7735 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryServicesProvidersImpl.java @@ -0,0 +1,117 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.RecoveryServicesProvider; + +class ReplicationRecoveryServicesProvidersImpl extends WrapperImpl implements ReplicationRecoveryServicesProviders { + private final RecoveryServicesManager manager; + + ReplicationRecoveryServicesProvidersImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationRecoveryServicesProviders()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public RecoveryServicesProviderImpl define(String name) { + return wrapModel(name); + } + + private RecoveryServicesProviderImpl wrapModel(RecoveryServicesProviderInner inner) { + return new RecoveryServicesProviderImpl(inner, manager()); + } + + private RecoveryServicesProviderImpl wrapModel(String name) { + return new RecoveryServicesProviderImpl(name, this.manager()); + } + + @Override + public Observable refreshProviderAsync(String fabricName, String providerName) { + ReplicationRecoveryServicesProvidersInner client = this.inner(); + return client.refreshProviderAsync(fabricName, providerName) + .map(new Func1() { + @Override + public RecoveryServicesProvider call(RecoveryServicesProviderInner inner) { + return new RecoveryServicesProviderImpl(inner, manager()); + } + }); + } + + @Override + public Completable deleteAsync(String fabricName, String providerName) { + ReplicationRecoveryServicesProvidersInner client = this.inner(); + return client.deleteAsync(fabricName, providerName).toCompletable(); + } + + @Override + public Observable listAsync() { + ReplicationRecoveryServicesProvidersInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public RecoveryServicesProvider call(RecoveryServicesProviderInner inner) { + return new RecoveryServicesProviderImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationFabricsAsync(final String fabricName) { + ReplicationRecoveryServicesProvidersInner client = this.inner(); + return client.listByReplicationFabricsAsync(fabricName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public RecoveryServicesProvider call(RecoveryServicesProviderInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String providerName) { + ReplicationRecoveryServicesProvidersInner client = this.inner(); + return client.getAsync(fabricName, providerName) + .map(new Func1() { + @Override + public RecoveryServicesProvider call(RecoveryServicesProviderInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable purgeAsync(String fabricName, String providerName) { + ReplicationRecoveryServicesProvidersInner client = this.inner(); + return client.purgeAsync(fabricName, providerName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryServicesProvidersInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryServicesProvidersInner.java new file mode 100644 index 0000000000000..027229eaeff12 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationRecoveryServicesProvidersInner.java @@ -0,0 +1,1414 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.collection.InnerSupportsDelete; +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.AddRecoveryServicesProviderInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.AddRecoveryServicesProviderInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationRecoveryServicesProviders. + */ +public class ReplicationRecoveryServicesProvidersInner implements InnerSupportsDelete { + /** The Retrofit service to perform REST calls. */ + private ReplicationRecoveryServicesProvidersService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationRecoveryServicesProvidersInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationRecoveryServicesProvidersInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationRecoveryServicesProvidersService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationRecoveryServicesProviders to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationRecoveryServicesProvidersService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders listByReplicationFabrics" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders") + Observable> listByReplicationFabrics(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body AddRecoveryServicesProviderInput addProviderInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body AddRecoveryServicesProviderInput addProviderInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders purge" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}", method = "DELETE", hasBody = true) + Observable> purge(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders beginPurge" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}", method = "DELETE", hasBody = true) + Observable> beginPurge(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders refreshProvider" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}/refreshProvider") + Observable> refreshProvider(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders beginRefreshProvider" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}/refreshProvider") + Observable> beginRefreshProvider(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders delete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}/remove") + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders beginDelete" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationRecoveryServicesProviders/{providerName}/remove") + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("providerName") String providerName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationRecoveryServicesProviders") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders listByReplicationFabricsNext" }) + @GET + Observable> listByReplicationFabricsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationRecoveryServicesProviders listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<RecoveryServicesProviderInner> object if successful. + */ + public PagedList listByReplicationFabrics(final String fabricName) { + ServiceResponse> response = listByReplicationFabricsSinglePageAsync(fabricName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param fabricName Fabric name + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsAsync(final String fabricName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsSinglePageAsync(fabricName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryServicesProviderInner> object + */ + public Observable> listByReplicationFabricsAsync(final String fabricName) { + return listByReplicationFabricsWithServiceResponseAsync(fabricName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryServicesProviderInner> object + */ + public Observable>> listByReplicationFabricsWithServiceResponseAsync(final String fabricName) { + return listByReplicationFabricsSinglePageAsync(fabricName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + ServiceResponse> * @param fabricName Fabric name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RecoveryServicesProviderInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsSinglePageAsync(final String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationFabrics(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the details of a recovery services provider. + * Gets the details of registered recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryServicesProviderInner object if successful. + */ + public RecoveryServicesProviderInner get(String fabricName, String providerName) { + return getWithServiceResponseAsync(fabricName, providerName).toBlocking().single().body(); + } + + /** + * Gets the details of a recovery services provider. + * Gets the details of registered recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String providerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, providerName), serviceCallback); + } + + /** + * Gets the details of a recovery services provider. + * Gets the details of registered recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryServicesProviderInner object + */ + public Observable getAsync(String fabricName, String providerName) { + return getWithServiceResponseAsync(fabricName, providerName).map(new Func1, RecoveryServicesProviderInner>() { + @Override + public RecoveryServicesProviderInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the details of a recovery services provider. + * Gets the details of registered recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryServicesProviderInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String providerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Adds a recovery services provider. + * The operation to add a recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param properties The properties of an add provider request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryServicesProviderInner object if successful. + */ + public RecoveryServicesProviderInner create(String fabricName, String providerName, AddRecoveryServicesProviderInputProperties properties) { + return createWithServiceResponseAsync(fabricName, providerName, properties).toBlocking().last().body(); + } + + /** + * Adds a recovery services provider. + * The operation to add a recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param properties The properties of an add provider request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String providerName, AddRecoveryServicesProviderInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, providerName, properties), serviceCallback); + } + + /** + * Adds a recovery services provider. + * The operation to add a recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param properties The properties of an add provider request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String providerName, AddRecoveryServicesProviderInputProperties properties) { + return createWithServiceResponseAsync(fabricName, providerName, properties).map(new Func1, RecoveryServicesProviderInner>() { + @Override + public RecoveryServicesProviderInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Adds a recovery services provider. + * The operation to add a recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param properties The properties of an add provider request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String providerName, AddRecoveryServicesProviderInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + AddRecoveryServicesProviderInput addProviderInput = new AddRecoveryServicesProviderInput(); + addProviderInput.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), addProviderInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Adds a recovery services provider. + * The operation to add a recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param properties The properties of an add provider request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryServicesProviderInner object if successful. + */ + public RecoveryServicesProviderInner beginCreate(String fabricName, String providerName, AddRecoveryServicesProviderInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, providerName, properties).toBlocking().single().body(); + } + + /** + * Adds a recovery services provider. + * The operation to add a recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param properties The properties of an add provider request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String providerName, AddRecoveryServicesProviderInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, providerName, properties), serviceCallback); + } + + /** + * Adds a recovery services provider. + * The operation to add a recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param properties The properties of an add provider request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryServicesProviderInner object + */ + public Observable beginCreateAsync(String fabricName, String providerName, AddRecoveryServicesProviderInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, providerName, properties).map(new Func1, RecoveryServicesProviderInner>() { + @Override + public RecoveryServicesProviderInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Adds a recovery services provider. + * The operation to add a recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param properties The properties of an add provider request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryServicesProviderInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String providerName, AddRecoveryServicesProviderInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (properties == null) { + throw new IllegalArgumentException("Parameter properties is required and cannot be null."); + } + Validator.validate(properties); + AddRecoveryServicesProviderInput addProviderInput = new AddRecoveryServicesProviderInput(); + addProviderInput.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), addProviderInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void purge(String fabricName, String providerName) { + purgeWithServiceResponseAsync(fabricName, providerName).toBlocking().last().body(); + } + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture purgeAsync(String fabricName, String providerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(purgeWithServiceResponseAsync(fabricName, providerName), serviceCallback); + } + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable purgeAsync(String fabricName, String providerName) { + return purgeWithServiceResponseAsync(fabricName, providerName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> purgeWithServiceResponseAsync(String fabricName, String providerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.purge(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginPurge(String fabricName, String providerName) { + beginPurgeWithServiceResponseAsync(fabricName, providerName).toBlocking().single().body(); + } + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginPurgeAsync(String fabricName, String providerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginPurgeWithServiceResponseAsync(fabricName, providerName), serviceCallback); + } + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginPurgeAsync(String fabricName, String providerName) { + return beginPurgeWithServiceResponseAsync(fabricName, providerName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Purges recovery service provider from fabric. + * The operation to purge(force delete) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginPurgeWithServiceResponseAsync(String fabricName, String providerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginPurge(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginPurgeDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginPurgeDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryServicesProviderInner object if successful. + */ + public RecoveryServicesProviderInner refreshProvider(String fabricName, String providerName) { + return refreshProviderWithServiceResponseAsync(fabricName, providerName).toBlocking().last().body(); + } + + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture refreshProviderAsync(String fabricName, String providerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(refreshProviderWithServiceResponseAsync(fabricName, providerName), serviceCallback); + } + + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable refreshProviderAsync(String fabricName, String providerName) { + return refreshProviderWithServiceResponseAsync(fabricName, providerName).map(new Func1, RecoveryServicesProviderInner>() { + @Override + public RecoveryServicesProviderInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> refreshProviderWithServiceResponseAsync(String fabricName, String providerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.refreshProvider(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the RecoveryServicesProviderInner object if successful. + */ + public RecoveryServicesProviderInner beginRefreshProvider(String fabricName, String providerName) { + return beginRefreshProviderWithServiceResponseAsync(fabricName, providerName).toBlocking().single().body(); + } + + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginRefreshProviderAsync(String fabricName, String providerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginRefreshProviderWithServiceResponseAsync(fabricName, providerName), serviceCallback); + } + + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryServicesProviderInner object + */ + public Observable beginRefreshProviderAsync(String fabricName, String providerName) { + return beginRefreshProviderWithServiceResponseAsync(fabricName, providerName).map(new Func1, RecoveryServicesProviderInner>() { + @Override + public RecoveryServicesProviderInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Refresh details from the recovery services provider. + * The operation to refresh the information from the recovery services provider. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RecoveryServicesProviderInner object + */ + public Observable> beginRefreshProviderWithServiceResponseAsync(String fabricName, String providerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginRefreshProvider(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginRefreshProviderDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginRefreshProviderDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String providerName) { + deleteWithServiceResponseAsync(fabricName, providerName).toBlocking().last().body(); + } + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String providerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, providerName), serviceCallback); + } + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String providerName) { + return deleteWithServiceResponseAsync(fabricName, providerName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String providerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String providerName) { + beginDeleteWithServiceResponseAsync(fabricName, providerName).toBlocking().single().body(); + } + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String providerName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, providerName), serviceCallback); + } + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String providerName) { + return beginDeleteWithServiceResponseAsync(fabricName, providerName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes provider from fabric. Note: Deleting provider for any fabric other than SingleHost is unsupported. To maintain backward compatibility for released clients the object "deleteRspInput" is used (if the object is empty we assume that it is old client and continue the old behavior). + * The operation to removes/delete(unregister) a recovery services provider from the vault. + * + * @param fabricName Fabric name. + * @param providerName Recovery services provider name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String providerName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (providerName == null) { + throw new IllegalArgumentException("Parameter providerName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, providerName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<RecoveryServicesProviderInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryServicesProviderInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryServicesProviderInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RecoveryServicesProviderInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<RecoveryServicesProviderInner> object if successful. + */ + public PagedList listByReplicationFabricsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryServicesProviderInner> object + */ + public Observable> listByReplicationFabricsNextAsync(final String nextPageLink) { + return listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryServicesProviderInner> object + */ + public Observable>> listByReplicationFabricsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of registered recovery services providers for the fabric. + * Lists the registered recovery services providers for the specified fabric. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RecoveryServicesProviderInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationFabricsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<RecoveryServicesProviderInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryServicesProviderInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RecoveryServicesProviderInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of registered recovery services providers in the vault. This is a view only api. + * Lists the registered recovery services providers in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RecoveryServicesProviderInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationMappingsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationMappingsImpl.java new file mode 100644 index 0000000000000..d3e10330aaa44 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationMappingsImpl.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassificationMapping; + +class ReplicationStorageClassificationMappingsImpl extends WrapperImpl implements ReplicationStorageClassificationMappings { + private final RecoveryServicesManager manager; + + ReplicationStorageClassificationMappingsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationStorageClassificationMappings()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public StorageClassificationMappingImpl define(String name) { + return wrapModel(name); + } + + private StorageClassificationMappingImpl wrapModel(StorageClassificationMappingInner inner) { + return new StorageClassificationMappingImpl(inner, manager()); + } + + private StorageClassificationMappingImpl wrapModel(String name) { + return new StorageClassificationMappingImpl(name, this.manager()); + } + + @Override + public Observable listAsync() { + ReplicationStorageClassificationMappingsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public StorageClassificationMapping call(StorageClassificationMappingInner inner) { + return new StorageClassificationMappingImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationStorageClassificationsAsync(final String fabricName, final String storageClassificationName) { + ReplicationStorageClassificationMappingsInner client = this.inner(); + return client.listByReplicationStorageClassificationsAsync(fabricName, storageClassificationName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public StorageClassificationMapping call(StorageClassificationMappingInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + ReplicationStorageClassificationMappingsInner client = this.inner(); + return client.getAsync(fabricName, storageClassificationName, storageClassificationMappingName) + .map(new Func1() { + @Override + public StorageClassificationMapping call(StorageClassificationMappingInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable deleteAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + ReplicationStorageClassificationMappingsInner client = this.inner(); + return client.deleteAsync(fabricName, storageClassificationName, storageClassificationMappingName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationMappingsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationMappingsInner.java new file mode 100644 index 0000000000000..1a383fe5386b5 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationMappingsInner.java @@ -0,0 +1,1270 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassificationMappingInput; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageMappingInputProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationStorageClassificationMappings. + */ +public class ReplicationStorageClassificationMappingsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationStorageClassificationMappingsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationStorageClassificationMappingsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationStorageClassificationMappingsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationStorageClassificationMappingsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationStorageClassificationMappings to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationStorageClassificationMappingsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings listByReplicationStorageClassifications" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings") + Observable> listByReplicationStorageClassifications(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("storageClassificationName") String storageClassificationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings/{storageClassificationMappingName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("storageClassificationName") String storageClassificationName, @Path("storageClassificationMappingName") String storageClassificationMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings/{storageClassificationMappingName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("storageClassificationName") String storageClassificationName, @Path("storageClassificationMappingName") String storageClassificationMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body StorageClassificationMappingInput pairingInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings/{storageClassificationMappingName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("storageClassificationName") String storageClassificationName, @Path("storageClassificationMappingName") String storageClassificationMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body StorageClassificationMappingInput pairingInput, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings delete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings/{storageClassificationMappingName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("storageClassificationName") String storageClassificationName, @Path("storageClassificationMappingName") String storageClassificationMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings beginDelete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}/replicationStorageClassificationMappings/{storageClassificationMappingName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("storageClassificationName") String storageClassificationName, @Path("storageClassificationMappingName") String storageClassificationMappingName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationStorageClassificationMappings") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings listByReplicationStorageClassificationsNext" }) + @GET + Observable> listByReplicationStorageClassificationsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassificationMappings listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<StorageClassificationMappingInner> object if successful. + */ + public PagedList listByReplicationStorageClassifications(final String fabricName, final String storageClassificationName) { + ServiceResponse> response = listByReplicationStorageClassificationsSinglePageAsync(fabricName, storageClassificationName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationStorageClassificationsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationStorageClassificationsAsync(final String fabricName, final String storageClassificationName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationStorageClassificationsSinglePageAsync(fabricName, storageClassificationName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationStorageClassificationsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationMappingInner> object + */ + public Observable> listByReplicationStorageClassificationsAsync(final String fabricName, final String storageClassificationName) { + return listByReplicationStorageClassificationsWithServiceResponseAsync(fabricName, storageClassificationName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationMappingInner> object + */ + public Observable>> listByReplicationStorageClassificationsWithServiceResponseAsync(final String fabricName, final String storageClassificationName) { + return listByReplicationStorageClassificationsSinglePageAsync(fabricName, storageClassificationName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationStorageClassificationsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + ServiceResponse> * @param fabricName Fabric name. + ServiceResponse> * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<StorageClassificationMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationStorageClassificationsSinglePageAsync(final String fabricName, final String storageClassificationName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationStorageClassifications(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationStorageClassificationsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationStorageClassificationsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the details of a storage classification mapping. + * Gets the details of the specified storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the StorageClassificationMappingInner object if successful. + */ + public StorageClassificationMappingInner get(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + return getWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).toBlocking().single().body(); + } + + /** + * Gets the details of a storage classification mapping. + * Gets the details of the specified storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName), serviceCallback); + } + + /** + * Gets the details of a storage classification mapping. + * Gets the details of the specified storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the StorageClassificationMappingInner object + */ + public Observable getAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + return getWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).map(new Func1, StorageClassificationMappingInner>() { + @Override + public StorageClassificationMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the details of a storage classification mapping. + * Gets the details of the specified storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the StorageClassificationMappingInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (storageClassificationMappingName == null) { + throw new IllegalArgumentException("Parameter storageClassificationMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, storageClassificationMappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the StorageClassificationMappingInner object if successful. + */ + public StorageClassificationMappingInner create(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + return createWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).toBlocking().last().body(); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName), serviceCallback); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + return createWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).map(new Func1, StorageClassificationMappingInner>() { + @Override + public StorageClassificationMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (storageClassificationMappingName == null) { + throw new IllegalArgumentException("Parameter storageClassificationMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final StorageMappingInputProperties properties = null; + StorageClassificationMappingInput pairingInput = new StorageClassificationMappingInput(); + pairingInput.withProperties(null); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, storageClassificationMappingName, this.client.apiVersion(), this.client.acceptLanguage(), pairingInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param properties Storage mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the StorageClassificationMappingInner object if successful. + */ + public StorageClassificationMappingInner create(String fabricName, String storageClassificationName, String storageClassificationMappingName, StorageMappingInputProperties properties) { + return createWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName, properties).toBlocking().last().body(); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param properties Storage mapping input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, StorageMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName, properties), serviceCallback); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param properties Storage mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, StorageMappingInputProperties properties) { + return createWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName, properties).map(new Func1, StorageClassificationMappingInner>() { + @Override + public StorageClassificationMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param properties Storage mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, StorageMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (storageClassificationMappingName == null) { + throw new IllegalArgumentException("Parameter storageClassificationMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + StorageClassificationMappingInput pairingInput = new StorageClassificationMappingInput(); + pairingInput.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, storageClassificationMappingName, this.client.apiVersion(), this.client.acceptLanguage(), pairingInput, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the StorageClassificationMappingInner object if successful. + */ + public StorageClassificationMappingInner beginCreate(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + return beginCreateWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).toBlocking().single().body(); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName), serviceCallback); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the StorageClassificationMappingInner object + */ + public Observable beginCreateAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + return beginCreateWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).map(new Func1, StorageClassificationMappingInner>() { + @Override + public StorageClassificationMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the StorageClassificationMappingInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (storageClassificationMappingName == null) { + throw new IllegalArgumentException("Parameter storageClassificationMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final StorageMappingInputProperties properties = null; + StorageClassificationMappingInput pairingInput = new StorageClassificationMappingInput(); + pairingInput.withProperties(null); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, storageClassificationMappingName, this.client.apiVersion(), this.client.acceptLanguage(), pairingInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param properties Storage mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the StorageClassificationMappingInner object if successful. + */ + public StorageClassificationMappingInner beginCreate(String fabricName, String storageClassificationName, String storageClassificationMappingName, StorageMappingInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName, properties).toBlocking().single().body(); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param properties Storage mapping input properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, StorageMappingInputProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName, properties), serviceCallback); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param properties Storage mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the StorageClassificationMappingInner object + */ + public Observable beginCreateAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, StorageMappingInputProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName, properties).map(new Func1, StorageClassificationMappingInner>() { + @Override + public StorageClassificationMappingInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create storage classification mapping. + * The operation to create a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param properties Storage mapping input properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the StorageClassificationMappingInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, StorageMappingInputProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (storageClassificationMappingName == null) { + throw new IllegalArgumentException("Parameter storageClassificationMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + StorageClassificationMappingInput pairingInput = new StorageClassificationMappingInput(); + pairingInput.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, storageClassificationMappingName, this.client.apiVersion(), this.client.acceptLanguage(), pairingInput, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + deleteWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).toBlocking().last().body(); + } + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName), serviceCallback); + } + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + return deleteWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (storageClassificationMappingName == null) { + throw new IllegalArgumentException("Parameter storageClassificationMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, storageClassificationMappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + beginDeleteWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).toBlocking().single().body(); + } + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName), serviceCallback); + } + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + return beginDeleteWithServiceResponseAsync(fabricName, storageClassificationName, storageClassificationMappingName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a storage classification mapping. + * The operation to delete a storage classification mapping. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param storageClassificationMappingName Storage classification mapping name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String storageClassificationName, String storageClassificationMappingName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (storageClassificationMappingName == null) { + throw new IllegalArgumentException("Parameter storageClassificationMappingName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, storageClassificationMappingName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<StorageClassificationMappingInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationMappingInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationMappingInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<StorageClassificationMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<StorageClassificationMappingInner> object if successful. + */ + public PagedList listByReplicationStorageClassificationsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationStorageClassificationsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationStorageClassificationsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationStorageClassificationsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationStorageClassificationsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationStorageClassificationsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationMappingInner> object + */ + public Observable> listByReplicationStorageClassificationsNextAsync(final String nextPageLink) { + return listByReplicationStorageClassificationsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationMappingInner> object + */ + public Observable>> listByReplicationStorageClassificationsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationStorageClassificationsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationStorageClassificationsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of storage classification mappings objects under a storage. + * Lists the storage classification mappings for the fabric. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<StorageClassificationMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationStorageClassificationsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationStorageClassificationsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationStorageClassificationsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationStorageClassificationsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<StorageClassificationMappingInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationMappingInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationMappingInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of storage classification mappings objects under a vault. + * Lists the storage classification mappings in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<StorageClassificationMappingInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationsImpl.java new file mode 100644 index 0000000000000..9e63970faf162 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationsImpl.java @@ -0,0 +1,83 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassifications; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassification; + +class ReplicationStorageClassificationsImpl extends WrapperImpl implements ReplicationStorageClassifications { + private final RecoveryServicesManager manager; + + ReplicationStorageClassificationsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationStorageClassifications()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private StorageClassificationImpl wrapModel(StorageClassificationInner inner) { + return new StorageClassificationImpl(inner, manager()); + } + + @Override + public Observable listAsync() { + ReplicationStorageClassificationsInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public StorageClassification call(StorageClassificationInner inner) { + return new StorageClassificationImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationFabricsAsync(final String fabricName) { + ReplicationStorageClassificationsInner client = this.inner(); + return client.listByReplicationFabricsAsync(fabricName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public StorageClassification call(StorageClassificationInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String storageClassificationName) { + ReplicationStorageClassificationsInner client = this.inner(); + return client.getAsync(fabricName, storageClassificationName) + .map(new Func1() { + @Override + public StorageClassification call(StorageClassificationInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationsInner.java new file mode 100644 index 0000000000000..edaf1b79b310b --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationStorageClassificationsInner.java @@ -0,0 +1,654 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationStorageClassifications. + */ +public class ReplicationStorageClassificationsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationStorageClassificationsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationStorageClassificationsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationStorageClassificationsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationStorageClassificationsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationStorageClassifications to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationStorageClassificationsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassifications listByReplicationFabrics" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications") + Observable> listByReplicationFabrics(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassifications get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationStorageClassifications/{storageClassificationName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("storageClassificationName") String storageClassificationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassifications list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationStorageClassifications") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassifications listByReplicationFabricsNext" }) + @GET + Observable> listByReplicationFabricsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationStorageClassifications listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param fabricName Site name of interest. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<StorageClassificationInner> object if successful. + */ + public PagedList listByReplicationFabrics(final String fabricName) { + ServiceResponse> response = listByReplicationFabricsSinglePageAsync(fabricName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param fabricName Site name of interest. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsAsync(final String fabricName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsSinglePageAsync(fabricName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param fabricName Site name of interest. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationInner> object + */ + public Observable> listByReplicationFabricsAsync(final String fabricName) { + return listByReplicationFabricsWithServiceResponseAsync(fabricName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param fabricName Site name of interest. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationInner> object + */ + public Observable>> listByReplicationFabricsWithServiceResponseAsync(final String fabricName) { + return listByReplicationFabricsSinglePageAsync(fabricName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + ServiceResponse> * @param fabricName Site name of interest. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<StorageClassificationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsSinglePageAsync(final String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationFabrics(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the details of a storage classification. + * Gets the details of the specified storage classification. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the StorageClassificationInner object if successful. + */ + public StorageClassificationInner get(String fabricName, String storageClassificationName) { + return getWithServiceResponseAsync(fabricName, storageClassificationName).toBlocking().single().body(); + } + + /** + * Gets the details of a storage classification. + * Gets the details of the specified storage classification. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String storageClassificationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, storageClassificationName), serviceCallback); + } + + /** + * Gets the details of a storage classification. + * Gets the details of the specified storage classification. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the StorageClassificationInner object + */ + public Observable getAsync(String fabricName, String storageClassificationName) { + return getWithServiceResponseAsync(fabricName, storageClassificationName).map(new Func1, StorageClassificationInner>() { + @Override + public StorageClassificationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the details of a storage classification. + * Gets the details of the specified storage classification. + * + * @param fabricName Fabric name. + * @param storageClassificationName Storage classification name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the StorageClassificationInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String storageClassificationName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (storageClassificationName == null) { + throw new IllegalArgumentException("Parameter storageClassificationName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, storageClassificationName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<StorageClassificationInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<StorageClassificationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<StorageClassificationInner> object if successful. + */ + public PagedList listByReplicationFabricsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationInner> object + */ + public Observable> listByReplicationFabricsNextAsync(final String nextPageLink) { + return listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationInner> object + */ + public Observable>> listByReplicationFabricsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of storage classification objects under a fabric. + * Lists the storage classifications available in the specified fabric. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<StorageClassificationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationFabricsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<StorageClassificationInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<StorageClassificationInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of storage classification objects under a vault. + * Lists the storage classifications in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<StorageClassificationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationVaultHealthsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationVaultHealthsImpl.java new file mode 100644 index 0000000000000..d456f4462e718 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationVaultHealthsImpl.java @@ -0,0 +1,54 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationVaultHealths; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.VaultHealthDetails; + +class ReplicationVaultHealthsImpl extends WrapperImpl implements ReplicationVaultHealths { + private final RecoveryServicesManager manager; + + ReplicationVaultHealthsImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationVaultHealths()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable getAsync() { + ReplicationVaultHealthsInner client = this.inner(); + return client.getAsync() + .map(new Func1() { + @Override + public VaultHealthDetails call(VaultHealthDetailsInner inner) { + return new VaultHealthDetailsImpl(inner, manager()); + } + }); + } + + @Override + public Observable refreshAsync() { + ReplicationVaultHealthsInner client = this.inner(); + return client.refreshAsync() + .map(new Func1() { + @Override + public VaultHealthDetails call(VaultHealthDetailsInner inner) { + return new VaultHealthDetailsImpl(inner, manager()); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationVaultHealthsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationVaultHealthsInner.java new file mode 100644 index 0000000000000..b35dd0e2b1f8e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationVaultHealthsInner.java @@ -0,0 +1,291 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.CloudException; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationVaultHealths. + */ +public class ReplicationVaultHealthsInner { + /** The Retrofit service to perform REST calls. */ + private ReplicationVaultHealthsService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationVaultHealthsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationVaultHealthsInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationVaultHealthsService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationVaultHealths to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationVaultHealthsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationVaultHealths get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationVaultHealth") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationVaultHealths refresh" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationVaultHealth/default/refresh") + Observable> refresh(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationVaultHealths beginRefresh" }) + @POST("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationVaultHealth/default/refresh") + Observable> beginRefresh(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the health summary for the vault. + * Gets the health details of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VaultHealthDetailsInner object if successful. + */ + public VaultHealthDetailsInner get() { + return getWithServiceResponseAsync().toBlocking().single().body(); + } + + /** + * Gets the health summary for the vault. + * Gets the health details of the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(), serviceCallback); + } + + /** + * Gets the health summary for the vault. + * Gets the health details of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VaultHealthDetailsInner object + */ + public Observable getAsync() { + return getWithServiceResponseAsync().map(new Func1, VaultHealthDetailsInner>() { + @Override + public VaultHealthDetailsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the health summary for the vault. + * Gets the health details of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VaultHealthDetailsInner object + */ + public Observable> getWithServiceResponseAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Refreshes health summary of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VaultHealthDetailsInner object if successful. + */ + public VaultHealthDetailsInner refresh() { + return refreshWithServiceResponseAsync().toBlocking().last().body(); + } + + /** + * Refreshes health summary of the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture refreshAsync(final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(refreshWithServiceResponseAsync(), serviceCallback); + } + + /** + * Refreshes health summary of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable refreshAsync() { + return refreshWithServiceResponseAsync().map(new Func1, VaultHealthDetailsInner>() { + @Override + public VaultHealthDetailsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Refreshes health summary of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> refreshWithServiceResponseAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.refresh(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Refreshes health summary of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VaultHealthDetailsInner object if successful. + */ + public VaultHealthDetailsInner beginRefresh() { + return beginRefreshWithServiceResponseAsync().toBlocking().single().body(); + } + + /** + * Refreshes health summary of the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginRefreshAsync(final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginRefreshWithServiceResponseAsync(), serviceCallback); + } + + /** + * Refreshes health summary of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VaultHealthDetailsInner object + */ + public Observable beginRefreshAsync() { + return beginRefreshWithServiceResponseAsync().map(new Func1, VaultHealthDetailsInner>() { + @Override + public VaultHealthDetailsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Refreshes health summary of the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VaultHealthDetailsInner object + */ + public Observable> beginRefreshWithServiceResponseAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginRefresh(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginRefreshDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginRefreshDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationvCentersImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationvCentersImpl.java new file mode 100644 index 0000000000000..852d2e9b9fee1 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationvCentersImpl.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.VCenter; + +class ReplicationvCentersImpl extends WrapperImpl implements ReplicationvCenters { + private final RecoveryServicesManager manager; + + ReplicationvCentersImpl(RecoveryServicesManager manager) { + super(manager.inner().replicationvCenters()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public VCenterImpl define(String name) { + return wrapModel(name); + } + + private VCenterImpl wrapModel(VCenterInner inner) { + return new VCenterImpl(inner, manager()); + } + + private VCenterImpl wrapModel(String name) { + return new VCenterImpl(name, this.manager()); + } + + @Override + public Observable listAsync() { + ReplicationvCentersInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public VCenter call(VCenterInner inner) { + return new VCenterImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByReplicationFabricsAsync(final String fabricName) { + ReplicationvCentersInner client = this.inner(); + return client.listByReplicationFabricsAsync(fabricName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public VCenter call(VCenterInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String fabricName, String vCenterName) { + ReplicationvCentersInner client = this.inner(); + return client.getAsync(fabricName, vCenterName) + .map(new Func1() { + @Override + public VCenter call(VCenterInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Completable deleteAsync(String fabricName, String vCenterName) { + ReplicationvCentersInner client = this.inner(); + return client.deleteAsync(fabricName, vCenterName).toCompletable(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationvCentersInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationvCentersInner.java new file mode 100644 index 0000000000000..3f4d6b12b8413 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/ReplicationvCentersInner.java @@ -0,0 +1,1588 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.collection.InnerSupportsDelete; +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.AddVCenterRequest; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.AddVCenterRequestProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateVCenterRequest; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateVCenterRequestProperties; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in ReplicationvCenters. + */ +public class ReplicationvCentersInner implements InnerSupportsDelete { + /** The Retrofit service to perform REST calls. */ + private ReplicationvCentersService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of ReplicationvCentersInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public ReplicationvCentersInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(ReplicationvCentersService.class); + this.client = client; + } + + /** + * The interface defining all the services for ReplicationvCenters to be + * used by Retrofit to perform actually REST calls. + */ + interface ReplicationvCentersService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters listByReplicationFabrics" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters") + Observable> listByReplicationFabrics(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters get" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}") + Observable> get(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("vCenterName") String vCenterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters create" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}") + Observable> create(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("vCenterName") String vCenterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body AddVCenterRequest addVCenterRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters beginCreate" }) + @PUT("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}") + Observable> beginCreate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("vCenterName") String vCenterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body AddVCenterRequest addVCenterRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters delete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("vCenterName") String vCenterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters beginDelete" }) + @HTTP(path = "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("vCenterName") String vCenterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters update" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}") + Observable> update(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("vCenterName") String vCenterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateVCenterRequest updateVCenterRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters beginUpdate" }) + @PATCH("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationvCenters/{vCenterName}") + Observable> beginUpdate(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("vCenterName") String vCenterName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UpdateVCenterRequest updateVCenterRequest, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters list" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationvCenters") + Observable> list(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters listByReplicationFabricsNext" }) + @GET + Observable> listByReplicationFabricsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.ReplicationvCenters listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<VCenterInner> object if successful. + */ + public PagedList listByReplicationFabrics(final String fabricName) { + ServiceResponse> response = listByReplicationFabricsSinglePageAsync(fabricName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param fabricName Fabric name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsAsync(final String fabricName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsSinglePageAsync(fabricName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<VCenterInner> object + */ + public Observable> listByReplicationFabricsAsync(final String fabricName) { + return listByReplicationFabricsWithServiceResponseAsync(fabricName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<VCenterInner> object + */ + public Observable>> listByReplicationFabricsWithServiceResponseAsync(final String fabricName) { + return listByReplicationFabricsSinglePageAsync(fabricName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + ServiceResponse> * @param fabricName Fabric name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<VCenterInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsSinglePageAsync(final String fabricName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationFabrics(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the details of a vCenter. + * Gets the details of a registered vCenter server(Add vCenter server.). + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner get(String fabricName, String vCenterName) { + return getWithServiceResponseAsync(fabricName, vCenterName).toBlocking().single().body(); + } + + /** + * Gets the details of a vCenter. + * Gets the details of a registered vCenter server(Add vCenter server.). + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String fabricName, String vCenterName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(fabricName, vCenterName), serviceCallback); + } + + /** + * Gets the details of a vCenter. + * Gets the details of a registered vCenter server(Add vCenter server.). + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable getAsync(String fabricName, String vCenterName) { + return getWithServiceResponseAsync(fabricName, vCenterName).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets the details of a vCenter. + * Gets the details of a registered vCenter server(Add vCenter server.). + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable> getWithServiceResponseAsync(String fabricName, String vCenterName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner create(String fabricName, String vCenterName) { + return createWithServiceResponseAsync(fabricName, vCenterName).toBlocking().last().body(); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String vCenterName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, vCenterName), serviceCallback); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String vCenterName) { + return createWithServiceResponseAsync(fabricName, vCenterName).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String vCenterName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final AddVCenterRequestProperties properties = null; + AddVCenterRequest addVCenterRequest = new AddVCenterRequest(); + addVCenterRequest.withProperties(null); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), addVCenterRequest, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param properties The properties of an add vCenter request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner create(String fabricName, String vCenterName, AddVCenterRequestProperties properties) { + return createWithServiceResponseAsync(fabricName, vCenterName, properties).toBlocking().last().body(); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param properties The properties of an add vCenter request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String fabricName, String vCenterName, AddVCenterRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(fabricName, vCenterName, properties), serviceCallback); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param properties The properties of an add vCenter request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String fabricName, String vCenterName, AddVCenterRequestProperties properties) { + return createWithServiceResponseAsync(fabricName, vCenterName, properties).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param properties The properties of an add vCenter request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String fabricName, String vCenterName, AddVCenterRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + AddVCenterRequest addVCenterRequest = new AddVCenterRequest(); + addVCenterRequest.withProperties(properties); + Observable> observable = service.create(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), addVCenterRequest, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner beginCreate(String fabricName, String vCenterName) { + return beginCreateWithServiceResponseAsync(fabricName, vCenterName).toBlocking().single().body(); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String vCenterName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, vCenterName), serviceCallback); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable beginCreateAsync(String fabricName, String vCenterName) { + return beginCreateWithServiceResponseAsync(fabricName, vCenterName).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String vCenterName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final AddVCenterRequestProperties properties = null; + AddVCenterRequest addVCenterRequest = new AddVCenterRequest(); + addVCenterRequest.withProperties(null); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), addVCenterRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param properties The properties of an add vCenter request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner beginCreate(String fabricName, String vCenterName, AddVCenterRequestProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, vCenterName, properties).toBlocking().single().body(); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param properties The properties of an add vCenter request. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String fabricName, String vCenterName, AddVCenterRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(fabricName, vCenterName, properties), serviceCallback); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param properties The properties of an add vCenter request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable beginCreateAsync(String fabricName, String vCenterName, AddVCenterRequestProperties properties) { + return beginCreateWithServiceResponseAsync(fabricName, vCenterName, properties).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Add vCenter. + * The operation to create a vCenter object.. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param properties The properties of an add vCenter request. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String fabricName, String vCenterName, AddVCenterRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + AddVCenterRequest addVCenterRequest = new AddVCenterRequest(); + addVCenterRequest.withProperties(properties); + return service.beginCreate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), addVCenterRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String fabricName, String vCenterName) { + deleteWithServiceResponseAsync(fabricName, vCenterName).toBlocking().last().body(); + } + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String fabricName, String vCenterName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(fabricName, vCenterName), serviceCallback); + } + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String fabricName, String vCenterName) { + return deleteWithServiceResponseAsync(fabricName, vCenterName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String fabricName, String vCenterName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String fabricName, String vCenterName) { + beginDeleteWithServiceResponseAsync(fabricName, vCenterName).toBlocking().single().body(); + } + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String fabricName, String vCenterName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(fabricName, vCenterName), serviceCallback); + } + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String fabricName, String vCenterName) { + return beginDeleteWithServiceResponseAsync(fabricName, vCenterName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Remove vCenter operation. + * The operation to remove(unregister) a registered vCenter server from the vault. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String fabricName, String vCenterName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner update(String fabricName, String vCenterName) { + return updateWithServiceResponseAsync(fabricName, vCenterName).toBlocking().last().body(); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String vCenterName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, vCenterName), serviceCallback); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String vCenterName) { + return updateWithServiceResponseAsync(fabricName, vCenterName).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String vCenterName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateVCenterRequestProperties properties = null; + UpdateVCenterRequest updateVCenterRequest = new UpdateVCenterRequest(); + updateVCenterRequest.withProperties(null); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), updateVCenterRequest, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param properties The update VCenter Request Properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner update(String fabricName, String vCenterName, UpdateVCenterRequestProperties properties) { + return updateWithServiceResponseAsync(fabricName, vCenterName, properties).toBlocking().last().body(); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param properties The update VCenter Request Properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String fabricName, String vCenterName, UpdateVCenterRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(fabricName, vCenterName, properties), serviceCallback); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param properties The update VCenter Request Properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable updateAsync(String fabricName, String vCenterName, UpdateVCenterRequestProperties properties) { + return updateWithServiceResponseAsync(fabricName, vCenterName, properties).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param properties The update VCenter Request Properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> updateWithServiceResponseAsync(String fabricName, String vCenterName, UpdateVCenterRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateVCenterRequest updateVCenterRequest = new UpdateVCenterRequest(); + updateVCenterRequest.withProperties(properties); + Observable> observable = service.update(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), updateVCenterRequest, this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner beginUpdate(String fabricName, String vCenterName) { + return beginUpdateWithServiceResponseAsync(fabricName, vCenterName).toBlocking().single().body(); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String vCenterName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, vCenterName), serviceCallback); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable beginUpdateAsync(String fabricName, String vCenterName) { + return beginUpdateWithServiceResponseAsync(fabricName, vCenterName).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String vCenterName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final UpdateVCenterRequestProperties properties = null; + UpdateVCenterRequest updateVCenterRequest = new UpdateVCenterRequest(); + updateVCenterRequest.withProperties(null); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), updateVCenterRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param properties The update VCenter Request Properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VCenterInner object if successful. + */ + public VCenterInner beginUpdate(String fabricName, String vCenterName, UpdateVCenterRequestProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, vCenterName, properties).toBlocking().single().body(); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param properties The update VCenter Request Properties. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginUpdateAsync(String fabricName, String vCenterName, UpdateVCenterRequestProperties properties, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(fabricName, vCenterName, properties), serviceCallback); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param properties The update VCenter Request Properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable beginUpdateAsync(String fabricName, String vCenterName, UpdateVCenterRequestProperties properties) { + return beginUpdateWithServiceResponseAsync(fabricName, vCenterName, properties).map(new Func1, VCenterInner>() { + @Override + public VCenterInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update vCenter operation. + * The operation to update a registered vCenter. + * + * @param fabricName Fabric name. + * @param vCenterName vCenter name + * @param properties The update VCenter Request Properties. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VCenterInner object + */ + public Observable> beginUpdateWithServiceResponseAsync(String fabricName, String vCenterName, UpdateVCenterRequestProperties properties) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (vCenterName == null) { + throw new IllegalArgumentException("Parameter vCenterName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(properties); + UpdateVCenterRequest updateVCenterRequest = new UpdateVCenterRequest(); + updateVCenterRequest.withProperties(properties); + return service.beginUpdate(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, vCenterName, this.client.apiVersion(), this.client.acceptLanguage(), updateVCenterRequest, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<VCenterInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<VCenterInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<VCenterInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<VCenterInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<VCenterInner> object if successful. + */ + public PagedList listByReplicationFabricsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationFabricsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationFabricsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<VCenterInner> object + */ + public Observable> listByReplicationFabricsNextAsync(final String nextPageLink) { + return listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<VCenterInner> object + */ + public Observable>> listByReplicationFabricsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationFabricsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationFabricsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of vCenter registered under a fabric. + * Lists the vCenter servers registered in a fabric. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<VCenterInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationFabricsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationFabricsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationFabricsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationFabricsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<VCenterInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<VCenterInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<VCenterInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of vCenter registered under the vault. + * Lists the vCenter servers registered in the vault. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<VCenterInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/SiteRecoveryManagementClientImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/SiteRecoveryManagementClientImpl.java new file mode 100644 index 0000000000000..5025b18140b52 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/SiteRecoveryManagementClientImpl.java @@ -0,0 +1,550 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.AzureClient; +import com.microsoft.azure.AzureServiceClient; +import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.microsoft.rest.RestClient; + +/** + * Initializes a new instance of the SiteRecoveryManagementClientImpl class. + */ +public class SiteRecoveryManagementClientImpl extends AzureServiceClient { + /** the {@link AzureClient} used for long running operations. */ + private AzureClient azureClient; + + /** + * Gets the {@link AzureClient} used for long running operations. + * @return the azure client; + */ + public AzureClient getAzureClient() { + return this.azureClient; + } + + /** The subscription Id. */ + private String subscriptionId; + + /** + * Gets The subscription Id. + * + * @return the subscriptionId value. + */ + public String subscriptionId() { + return this.subscriptionId; + } + + /** + * Sets The subscription Id. + * + * @param subscriptionId the subscriptionId value. + * @return the service client itself + */ + public SiteRecoveryManagementClientImpl withSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /** The name of the resource group where the recovery services vault is present. */ + private String resourceGroupName; + + /** + * Gets The name of the resource group where the recovery services vault is present. + * + * @return the resourceGroupName value. + */ + public String resourceGroupName() { + return this.resourceGroupName; + } + + /** + * Sets The name of the resource group where the recovery services vault is present. + * + * @param resourceGroupName the resourceGroupName value. + * @return the service client itself + */ + public SiteRecoveryManagementClientImpl withResourceGroupName(String resourceGroupName) { + this.resourceGroupName = resourceGroupName; + return this; + } + + /** The name of the recovery services vault. */ + private String resourceName; + + /** + * Gets The name of the recovery services vault. + * + * @return the resourceName value. + */ + public String resourceName() { + return this.resourceName; + } + + /** + * Sets The name of the recovery services vault. + * + * @param resourceName the resourceName value. + * @return the service client itself + */ + public SiteRecoveryManagementClientImpl withResourceName(String resourceName) { + this.resourceName = resourceName; + return this; + } + + /** Client Api Version. */ + private String apiVersion; + + /** + * Gets Client Api Version. + * + * @return the apiVersion value. + */ + public String apiVersion() { + return this.apiVersion; + } + + /** The preferred language for the response. */ + private String acceptLanguage; + + /** + * Gets The preferred language for the response. + * + * @return the acceptLanguage value. + */ + public String acceptLanguage() { + return this.acceptLanguage; + } + + /** + * Sets The preferred language for the response. + * + * @param acceptLanguage the acceptLanguage value. + * @return the service client itself + */ + public SiteRecoveryManagementClientImpl withAcceptLanguage(String acceptLanguage) { + this.acceptLanguage = acceptLanguage; + return this; + } + + /** The retry timeout in seconds for Long Running Operations. Default value is 30. */ + private int longRunningOperationRetryTimeout; + + /** + * Gets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @return the longRunningOperationRetryTimeout value. + */ + public int longRunningOperationRetryTimeout() { + return this.longRunningOperationRetryTimeout; + } + + /** + * Sets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. + * @return the service client itself + */ + public SiteRecoveryManagementClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { + this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; + return this; + } + + /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ + private boolean generateClientRequestId; + + /** + * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @return the generateClientRequestId value. + */ + public boolean generateClientRequestId() { + return this.generateClientRequestId; + } + + /** + * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @param generateClientRequestId the generateClientRequestId value. + * @return the service client itself + */ + public SiteRecoveryManagementClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { + this.generateClientRequestId = generateClientRequestId; + return this; + } + + /** + * The OperationsInner object to access its operations. + */ + private OperationsInner operations; + + /** + * Gets the OperationsInner object to access its operations. + * @return the OperationsInner object. + */ + public OperationsInner operations() { + return this.operations; + } + + /** + * The ReplicationAlertSettingsInner object to access its operations. + */ + private ReplicationAlertSettingsInner replicationAlertSettings; + + /** + * Gets the ReplicationAlertSettingsInner object to access its operations. + * @return the ReplicationAlertSettingsInner object. + */ + public ReplicationAlertSettingsInner replicationAlertSettings() { + return this.replicationAlertSettings; + } + + /** + * The ReplicationEventsInner object to access its operations. + */ + private ReplicationEventsInner replicationEvents; + + /** + * Gets the ReplicationEventsInner object to access its operations. + * @return the ReplicationEventsInner object. + */ + public ReplicationEventsInner replicationEvents() { + return this.replicationEvents; + } + + /** + * The ReplicationFabricsInner object to access its operations. + */ + private ReplicationFabricsInner replicationFabrics; + + /** + * Gets the ReplicationFabricsInner object to access its operations. + * @return the ReplicationFabricsInner object. + */ + public ReplicationFabricsInner replicationFabrics() { + return this.replicationFabrics; + } + + /** + * The ReplicationLogicalNetworksInner object to access its operations. + */ + private ReplicationLogicalNetworksInner replicationLogicalNetworks; + + /** + * Gets the ReplicationLogicalNetworksInner object to access its operations. + * @return the ReplicationLogicalNetworksInner object. + */ + public ReplicationLogicalNetworksInner replicationLogicalNetworks() { + return this.replicationLogicalNetworks; + } + + /** + * The ReplicationNetworksInner object to access its operations. + */ + private ReplicationNetworksInner replicationNetworks; + + /** + * Gets the ReplicationNetworksInner object to access its operations. + * @return the ReplicationNetworksInner object. + */ + public ReplicationNetworksInner replicationNetworks() { + return this.replicationNetworks; + } + + /** + * The ReplicationNetworkMappingsInner object to access its operations. + */ + private ReplicationNetworkMappingsInner replicationNetworkMappings; + + /** + * Gets the ReplicationNetworkMappingsInner object to access its operations. + * @return the ReplicationNetworkMappingsInner object. + */ + public ReplicationNetworkMappingsInner replicationNetworkMappings() { + return this.replicationNetworkMappings; + } + + /** + * The ReplicationProtectionContainersInner object to access its operations. + */ + private ReplicationProtectionContainersInner replicationProtectionContainers; + + /** + * Gets the ReplicationProtectionContainersInner object to access its operations. + * @return the ReplicationProtectionContainersInner object. + */ + public ReplicationProtectionContainersInner replicationProtectionContainers() { + return this.replicationProtectionContainers; + } + + /** + * The ReplicationMigrationItemsInner object to access its operations. + */ + private ReplicationMigrationItemsInner replicationMigrationItems; + + /** + * Gets the ReplicationMigrationItemsInner object to access its operations. + * @return the ReplicationMigrationItemsInner object. + */ + public ReplicationMigrationItemsInner replicationMigrationItems() { + return this.replicationMigrationItems; + } + + /** + * The MigrationRecoveryPointsInner object to access its operations. + */ + private MigrationRecoveryPointsInner migrationRecoveryPoints; + + /** + * Gets the MigrationRecoveryPointsInner object to access its operations. + * @return the MigrationRecoveryPointsInner object. + */ + public MigrationRecoveryPointsInner migrationRecoveryPoints() { + return this.migrationRecoveryPoints; + } + + /** + * The ReplicationProtectableItemsInner object to access its operations. + */ + private ReplicationProtectableItemsInner replicationProtectableItems; + + /** + * Gets the ReplicationProtectableItemsInner object to access its operations. + * @return the ReplicationProtectableItemsInner object. + */ + public ReplicationProtectableItemsInner replicationProtectableItems() { + return this.replicationProtectableItems; + } + + /** + * The ReplicationProtectedItemsInner object to access its operations. + */ + private ReplicationProtectedItemsInner replicationProtectedItems; + + /** + * Gets the ReplicationProtectedItemsInner object to access its operations. + * @return the ReplicationProtectedItemsInner object. + */ + public ReplicationProtectedItemsInner replicationProtectedItems() { + return this.replicationProtectedItems; + } + + /** + * The RecoveryPointsInner object to access its operations. + */ + private RecoveryPointsInner recoveryPoints; + + /** + * Gets the RecoveryPointsInner object to access its operations. + * @return the RecoveryPointsInner object. + */ + public RecoveryPointsInner recoveryPoints() { + return this.recoveryPoints; + } + + /** + * The TargetComputeSizesInner object to access its operations. + */ + private TargetComputeSizesInner targetComputeSizes; + + /** + * Gets the TargetComputeSizesInner object to access its operations. + * @return the TargetComputeSizesInner object. + */ + public TargetComputeSizesInner targetComputeSizes() { + return this.targetComputeSizes; + } + + /** + * The ReplicationProtectionContainerMappingsInner object to access its operations. + */ + private ReplicationProtectionContainerMappingsInner replicationProtectionContainerMappings; + + /** + * Gets the ReplicationProtectionContainerMappingsInner object to access its operations. + * @return the ReplicationProtectionContainerMappingsInner object. + */ + public ReplicationProtectionContainerMappingsInner replicationProtectionContainerMappings() { + return this.replicationProtectionContainerMappings; + } + + /** + * The ReplicationRecoveryServicesProvidersInner object to access its operations. + */ + private ReplicationRecoveryServicesProvidersInner replicationRecoveryServicesProviders; + + /** + * Gets the ReplicationRecoveryServicesProvidersInner object to access its operations. + * @return the ReplicationRecoveryServicesProvidersInner object. + */ + public ReplicationRecoveryServicesProvidersInner replicationRecoveryServicesProviders() { + return this.replicationRecoveryServicesProviders; + } + + /** + * The ReplicationStorageClassificationsInner object to access its operations. + */ + private ReplicationStorageClassificationsInner replicationStorageClassifications; + + /** + * Gets the ReplicationStorageClassificationsInner object to access its operations. + * @return the ReplicationStorageClassificationsInner object. + */ + public ReplicationStorageClassificationsInner replicationStorageClassifications() { + return this.replicationStorageClassifications; + } + + /** + * The ReplicationStorageClassificationMappingsInner object to access its operations. + */ + private ReplicationStorageClassificationMappingsInner replicationStorageClassificationMappings; + + /** + * Gets the ReplicationStorageClassificationMappingsInner object to access its operations. + * @return the ReplicationStorageClassificationMappingsInner object. + */ + public ReplicationStorageClassificationMappingsInner replicationStorageClassificationMappings() { + return this.replicationStorageClassificationMappings; + } + + /** + * The ReplicationvCentersInner object to access its operations. + */ + private ReplicationvCentersInner replicationvCenters; + + /** + * Gets the ReplicationvCentersInner object to access its operations. + * @return the ReplicationvCentersInner object. + */ + public ReplicationvCentersInner replicationvCenters() { + return this.replicationvCenters; + } + + /** + * The ReplicationJobsInner object to access its operations. + */ + private ReplicationJobsInner replicationJobs; + + /** + * Gets the ReplicationJobsInner object to access its operations. + * @return the ReplicationJobsInner object. + */ + public ReplicationJobsInner replicationJobs() { + return this.replicationJobs; + } + + /** + * The ReplicationPoliciesInner object to access its operations. + */ + private ReplicationPoliciesInner replicationPolicies; + + /** + * Gets the ReplicationPoliciesInner object to access its operations. + * @return the ReplicationPoliciesInner object. + */ + public ReplicationPoliciesInner replicationPolicies() { + return this.replicationPolicies; + } + + /** + * The ReplicationRecoveryPlansInner object to access its operations. + */ + private ReplicationRecoveryPlansInner replicationRecoveryPlans; + + /** + * Gets the ReplicationRecoveryPlansInner object to access its operations. + * @return the ReplicationRecoveryPlansInner object. + */ + public ReplicationRecoveryPlansInner replicationRecoveryPlans() { + return this.replicationRecoveryPlans; + } + + /** + * The ReplicationVaultHealthsInner object to access its operations. + */ + private ReplicationVaultHealthsInner replicationVaultHealths; + + /** + * Gets the ReplicationVaultHealthsInner object to access its operations. + * @return the ReplicationVaultHealthsInner object. + */ + public ReplicationVaultHealthsInner replicationVaultHealths() { + return this.replicationVaultHealths; + } + + /** + * Initializes an instance of SiteRecoveryManagementClient client. + * + * @param credentials the management credentials for Azure + */ + public SiteRecoveryManagementClientImpl(ServiceClientCredentials credentials) { + this("https://management.azure.com", credentials); + } + + /** + * Initializes an instance of SiteRecoveryManagementClient client. + * + * @param baseUrl the base URL of the host + * @param credentials the management credentials for Azure + */ + public SiteRecoveryManagementClientImpl(String baseUrl, ServiceClientCredentials credentials) { + super(baseUrl, credentials); + initialize(); + } + + /** + * Initializes an instance of SiteRecoveryManagementClient client. + * + * @param restClient the REST client to connect to Azure. + */ + public SiteRecoveryManagementClientImpl(RestClient restClient) { + super(restClient); + initialize(); + } + + protected void initialize() { + this.apiVersion = "2018-01-10"; + this.acceptLanguage = "en-US"; + this.longRunningOperationRetryTimeout = 30; + this.generateClientRequestId = true; + this.operations = new OperationsInner(restClient().retrofit(), this); + this.replicationAlertSettings = new ReplicationAlertSettingsInner(restClient().retrofit(), this); + this.replicationEvents = new ReplicationEventsInner(restClient().retrofit(), this); + this.replicationFabrics = new ReplicationFabricsInner(restClient().retrofit(), this); + this.replicationLogicalNetworks = new ReplicationLogicalNetworksInner(restClient().retrofit(), this); + this.replicationNetworks = new ReplicationNetworksInner(restClient().retrofit(), this); + this.replicationNetworkMappings = new ReplicationNetworkMappingsInner(restClient().retrofit(), this); + this.replicationProtectionContainers = new ReplicationProtectionContainersInner(restClient().retrofit(), this); + this.replicationMigrationItems = new ReplicationMigrationItemsInner(restClient().retrofit(), this); + this.migrationRecoveryPoints = new MigrationRecoveryPointsInner(restClient().retrofit(), this); + this.replicationProtectableItems = new ReplicationProtectableItemsInner(restClient().retrofit(), this); + this.replicationProtectedItems = new ReplicationProtectedItemsInner(restClient().retrofit(), this); + this.recoveryPoints = new RecoveryPointsInner(restClient().retrofit(), this); + this.targetComputeSizes = new TargetComputeSizesInner(restClient().retrofit(), this); + this.replicationProtectionContainerMappings = new ReplicationProtectionContainerMappingsInner(restClient().retrofit(), this); + this.replicationRecoveryServicesProviders = new ReplicationRecoveryServicesProvidersInner(restClient().retrofit(), this); + this.replicationStorageClassifications = new ReplicationStorageClassificationsInner(restClient().retrofit(), this); + this.replicationStorageClassificationMappings = new ReplicationStorageClassificationMappingsInner(restClient().retrofit(), this); + this.replicationvCenters = new ReplicationvCentersInner(restClient().retrofit(), this); + this.replicationJobs = new ReplicationJobsInner(restClient().retrofit(), this); + this.replicationPolicies = new ReplicationPoliciesInner(restClient().retrofit(), this); + this.replicationRecoveryPlans = new ReplicationRecoveryPlansInner(restClient().retrofit(), this); + this.replicationVaultHealths = new ReplicationVaultHealthsInner(restClient().retrofit(), this); + this.azureClient = new AzureClient(this); + } + + /** + * Gets the User-Agent header for the client. + * + * @return the user agent string. + */ + @Override + public String userAgent() { + return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "SiteRecoveryManagementClient", "2018-01-10"); + } +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationImpl.java new file mode 100644 index 0000000000000..cc5603cec3665 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationImpl.java @@ -0,0 +1,67 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassification; +import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassificationProperties; + +class StorageClassificationImpl extends IndexableRefreshableWrapperImpl implements StorageClassification { + private final RecoveryServicesManager manager; + private String fabricName; + private String storageClassificationName; + + StorageClassificationImpl(StorageClassificationInner inner, RecoveryServicesManager manager) { + super(null, inner); + this.manager = manager; + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.storageClassificationName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationStorageClassifications"); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + protected Observable getInnerAsync() { + ReplicationStorageClassificationsInner client = this.manager().inner().replicationStorageClassifications(); + return client.getAsync(this.fabricName, this.storageClassificationName); + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public StorageClassificationProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationInner.java new file mode 100644 index 0000000000000..7243a22b0f640 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassificationProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Storage object definition. + */ +public class StorageClassificationInner extends ProxyResource { + /** + * Properties of the storage object. + */ + @JsonProperty(value = "properties") + private StorageClassificationProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get properties of the storage object. + * + * @return the properties value + */ + public StorageClassificationProperties properties() { + return this.properties; + } + + /** + * Set properties of the storage object. + * + * @param properties the properties value to set + * @return the StorageClassificationInner object itself. + */ + public StorageClassificationInner withProperties(StorageClassificationProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the StorageClassificationInner object itself. + */ + public StorageClassificationInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationMappingImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationMappingImpl.java new file mode 100644 index 0000000000000..1cda9856e7f8e --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationMappingImpl.java @@ -0,0 +1,141 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassificationMapping; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageMappingInputProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassificationMappingProperties; +import rx.functions.Func1; + +class StorageClassificationMappingImpl extends CreatableUpdatableImpl implements StorageClassificationMapping, StorageClassificationMapping.Definition, StorageClassificationMapping.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private String storageClassificationName; + private String storageClassificationMappingName; + private StorageMappingInputProperties cproperties; + private StorageMappingInputProperties uproperties; + + StorageClassificationMappingImpl(String name, RecoveryServicesManager manager) { + super(name, new StorageClassificationMappingInner()); + this.manager = manager; + // Set resource name + this.storageClassificationMappingName = name; + // + this.cproperties = new StorageMappingInputProperties(); + this.uproperties = new StorageMappingInputProperties(); + } + + StorageClassificationMappingImpl(StorageClassificationMappingInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.storageClassificationMappingName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.storageClassificationName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationStorageClassifications"); + this.storageClassificationMappingName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationStorageClassificationMappings"); + // + this.cproperties = new StorageMappingInputProperties(); + this.uproperties = new StorageMappingInputProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationStorageClassificationMappingsInner client = this.manager().inner().replicationStorageClassificationMappings(); + return client.createAsync(this.fabricName, this.storageClassificationName, this.storageClassificationMappingName, this.cproperties) + .map(new Func1() { + @Override + public StorageClassificationMappingInner call(StorageClassificationMappingInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationStorageClassificationMappingsInner client = this.manager().inner().replicationStorageClassificationMappings(); + return client.createAsync(this.fabricName, this.storageClassificationName, this.storageClassificationMappingName, this.uproperties) + .map(new Func1() { + @Override + public StorageClassificationMappingInner call(StorageClassificationMappingInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationStorageClassificationMappingsInner client = this.manager().inner().replicationStorageClassificationMappings(); + return client.getAsync(this.fabricName, this.storageClassificationName, this.storageClassificationMappingName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new StorageMappingInputProperties(); + this.uproperties = new StorageMappingInputProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public StorageClassificationMappingProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public StorageClassificationMappingImpl withExistingReplicationStorageClassification(String fabricName, String storageClassificationName) { + this.fabricName = fabricName; + this.storageClassificationName = storageClassificationName; + return this; + } + + @Override + public StorageClassificationMappingImpl withProperties(StorageMappingInputProperties properties) { + if (isInCreateMode()) { + this.cproperties = properties; + } else { + this.uproperties = properties; + } + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationMappingInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationMappingInner.java new file mode 100644 index 0000000000000..8f91fec845d27 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/StorageClassificationMappingInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.StorageClassificationMappingProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Storage mapping object. + */ +public class StorageClassificationMappingInner extends ProxyResource { + /** + * Properties of the storage mapping object. + */ + @JsonProperty(value = "properties") + private StorageClassificationMappingProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get properties of the storage mapping object. + * + * @return the properties value + */ + public StorageClassificationMappingProperties properties() { + return this.properties; + } + + /** + * Set properties of the storage mapping object. + * + * @param properties the properties value to set + * @return the StorageClassificationMappingInner object itself. + */ + public StorageClassificationMappingInner withProperties(StorageClassificationMappingProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the StorageClassificationMappingInner object itself. + */ + public StorageClassificationMappingInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizeImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizeImpl.java new file mode 100644 index 0000000000000..a94d301dc78bc --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizeImpl.java @@ -0,0 +1,51 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TargetComputeSize; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TargetComputeSizeProperties; + +class TargetComputeSizeImpl extends WrapperImpl implements TargetComputeSize { + private final RecoveryServicesManager manager; + + TargetComputeSizeImpl(TargetComputeSizeInner inner, RecoveryServicesManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public TargetComputeSizeProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizeInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizeInner.java new file mode 100644 index 0000000000000..28a060a6a3fd0 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizeInner.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TargetComputeSizeProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents applicable recovery vm sizes. + */ +public class TargetComputeSizeInner { + /** + * The Id. + */ + @JsonProperty(value = "id") + private String id; + + /** + * The name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * The Type of the object. + */ + @JsonProperty(value = "type") + private String type; + + /** + * The custom data. + */ + @JsonProperty(value = "properties") + private TargetComputeSizeProperties properties; + + /** + * Get the Id. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Set the Id. + * + * @param id the id value to set + * @return the TargetComputeSizeInner object itself. + */ + public TargetComputeSizeInner withId(String id) { + this.id = id; + return this; + } + + /** + * Get the name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set the name. + * + * @param name the name value to set + * @return the TargetComputeSizeInner object itself. + */ + public TargetComputeSizeInner withName(String name) { + this.name = name; + return this; + } + + /** + * Get the Type of the object. + * + * @return the type value + */ + public String type() { + return this.type; + } + + /** + * Set the Type of the object. + * + * @param type the type value to set + * @return the TargetComputeSizeInner object itself. + */ + public TargetComputeSizeInner withType(String type) { + this.type = type; + return this; + } + + /** + * Get the custom data. + * + * @return the properties value + */ + public TargetComputeSizeProperties properties() { + return this.properties; + } + + /** + * Set the custom data. + * + * @param properties the properties value to set + * @return the TargetComputeSizeInner object itself. + */ + public TargetComputeSizeInner withProperties(TargetComputeSizeProperties properties) { + this.properties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizesImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizesImpl.java new file mode 100644 index 0000000000000..f347e994a0e11 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizesImpl.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TargetComputeSizes; +import rx.Observable; +import rx.functions.Func1; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TargetComputeSize; + +class TargetComputeSizesImpl extends WrapperImpl implements TargetComputeSizes { + private final RecoveryServicesManager manager; + + TargetComputeSizesImpl(RecoveryServicesManager manager) { + super(manager.inner().targetComputeSizes()); + this.manager = manager; + } + + public RecoveryServicesManager manager() { + return this.manager; + } + + private TargetComputeSizeImpl wrapModel(TargetComputeSizeInner inner) { + return new TargetComputeSizeImpl(inner, manager()); + } + + @Override + public Observable listByReplicationProtectedItemsAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + TargetComputeSizesInner client = this.inner(); + return client.listByReplicationProtectedItemsAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public TargetComputeSize call(TargetComputeSizeInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizesInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizesInner.java new file mode 100644 index 0000000000000..ade5aa518aaca --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/TargetComputeSizesInner.java @@ -0,0 +1,327 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in TargetComputeSizes. + */ +public class TargetComputeSizesInner { + /** The Retrofit service to perform REST calls. */ + private TargetComputeSizesService service; + /** The service client containing this operation class. */ + private SiteRecoveryManagementClientImpl client; + + /** + * Initializes an instance of TargetComputeSizesInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public TargetComputeSizesInner(Retrofit retrofit, SiteRecoveryManagementClientImpl client) { + this.service = retrofit.create(TargetComputeSizesService.class); + this.client = client; + } + + /** + * The interface defining all the services for TargetComputeSizes to be + * used by Retrofit to perform actually REST calls. + */ + interface TargetComputeSizesService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TargetComputeSizes listByReplicationProtectedItems" }) + @GET("Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationProtectedItems/{replicatedProtectedItemName}/targetComputeSizes") + Observable> listByReplicationProtectedItems(@Path("resourceName") String resourceName, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("fabricName") String fabricName, @Path("protectionContainerName") String protectionContainerName, @Path("replicatedProtectedItemName") String replicatedProtectedItemName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.TargetComputeSizes listByReplicationProtectedItemsNext" }) + @GET + Observable> listByReplicationProtectedItemsNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<TargetComputeSizeInner> object if successful. + */ + public PagedList listByReplicationProtectedItems(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + ServiceResponse> response = listByReplicationProtectedItemsSinglePageAsync(fabricName, protectionContainerName, replicatedProtectedItemName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectedItemsAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectedItemsSinglePageAsync(fabricName, protectionContainerName, replicatedProtectedItemName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<TargetComputeSizeInner> object + */ + public Observable> listByReplicationProtectedItemsAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + return listByReplicationProtectedItemsWithServiceResponseAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param fabricName Fabric name. + * @param protectionContainerName protection container name. + * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<TargetComputeSizeInner> object + */ + public Observable>> listByReplicationProtectedItemsWithServiceResponseAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + return listByReplicationProtectedItemsSinglePageAsync(fabricName, protectionContainerName, replicatedProtectedItemName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectedItemsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + ServiceResponse> * @param fabricName Fabric name. + ServiceResponse> * @param protectionContainerName protection container name. + ServiceResponse> * @param replicatedProtectedItemName Replication protected item name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<TargetComputeSizeInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectedItemsSinglePageAsync(final String fabricName, final String protectionContainerName, final String replicatedProtectedItemName) { + if (this.client.resourceName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceName() is required and cannot be null."); + } + if (this.client.resourceGroupName() == null) { + throw new IllegalArgumentException("Parameter this.client.resourceGroupName() is required and cannot be null."); + } + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (fabricName == null) { + throw new IllegalArgumentException("Parameter fabricName is required and cannot be null."); + } + if (protectionContainerName == null) { + throw new IllegalArgumentException("Parameter protectionContainerName is required and cannot be null."); + } + if (replicatedProtectedItemName == null) { + throw new IllegalArgumentException("Parameter replicatedProtectedItemName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByReplicationProtectedItems(this.client.resourceName(), this.client.resourceGroupName(), this.client.subscriptionId(), fabricName, protectionContainerName, replicatedProtectedItemName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectedItemsDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectedItemsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<TargetComputeSizeInner> object if successful. + */ + public PagedList listByReplicationProtectedItemsNext(final String nextPageLink) { + ServiceResponse> response = listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByReplicationProtectedItemsNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<TargetComputeSizeInner> object + */ + public Observable> listByReplicationProtectedItemsNextAsync(final String nextPageLink) { + return listByReplicationProtectedItemsNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<TargetComputeSizeInner> object + */ + public Observable>> listByReplicationProtectedItemsNextWithServiceResponseAsync(final String nextPageLink) { + return listByReplicationProtectedItemsNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByReplicationProtectedItemsNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets the list of target compute sizes for the replication protected item. + * Lists the available target compute sizes for a replication protected item. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<TargetComputeSizeInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByReplicationProtectedItemsNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByReplicationProtectedItemsNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByReplicationProtectedItemsNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByReplicationProtectedItemsNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VCenterImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VCenterImpl.java new file mode 100644 index 0000000000000..934e6cb2ce978 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VCenterImpl.java @@ -0,0 +1,141 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.VCenter; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.UpdateVCenterRequestProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.AddVCenterRequestProperties; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.VCenterProperties; +import rx.functions.Func1; + +class VCenterImpl extends CreatableUpdatableImpl implements VCenter, VCenter.Definition, VCenter.Update { + private final RecoveryServicesManager manager; + private String fabricName; + private String vCenterName; + private AddVCenterRequestProperties cproperties; + private UpdateVCenterRequestProperties uproperties; + + VCenterImpl(String name, RecoveryServicesManager manager) { + super(name, new VCenterInner()); + this.manager = manager; + // Set resource name + this.vCenterName = name; + // + this.cproperties = new AddVCenterRequestProperties(); + this.uproperties = new UpdateVCenterRequestProperties(); + } + + VCenterImpl(VCenterInner inner, RecoveryServicesManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.vCenterName = inner.name(); + // set resource ancestor and positional variables + this.fabricName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationFabrics"); + this.vCenterName = IdParsingUtils.getValueFromIdByName(inner.id(), "replicationvCenters"); + // + this.cproperties = new AddVCenterRequestProperties(); + this.uproperties = new UpdateVCenterRequestProperties(); + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + ReplicationvCentersInner client = this.manager().inner().replicationvCenters(); + return client.createAsync(this.fabricName, this.vCenterName, this.cproperties) + .map(new Func1() { + @Override + public VCenterInner call(VCenterInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + ReplicationvCentersInner client = this.manager().inner().replicationvCenters(); + return client.updateAsync(this.fabricName, this.vCenterName, this.uproperties) + .map(new Func1() { + @Override + public VCenterInner call(VCenterInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + ReplicationvCentersInner client = this.manager().inner().replicationvCenters(); + return client.getAsync(this.fabricName, this.vCenterName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.cproperties = new AddVCenterRequestProperties(); + this.uproperties = new UpdateVCenterRequestProperties(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public VCenterProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public VCenterImpl withExistingReplicationFabric(String fabricName) { + this.fabricName = fabricName; + return this; + } + + @Override + public VCenterImpl withProperties(AddVCenterRequestProperties properties) { + this.cproperties = properties; + return this; + } + + @Override + public VCenterImpl withProperties(UpdateVCenterRequestProperties properties) { + this.uproperties = properties; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VCenterInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VCenterInner.java new file mode 100644 index 0000000000000..30aa515a1ffa4 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VCenterInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.VCenterProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * vCenter definition. + */ +public class VCenterInner extends ProxyResource { + /** + * VCenter related data. + */ + @JsonProperty(value = "properties") + private VCenterProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get vCenter related data. + * + * @return the properties value + */ + public VCenterProperties properties() { + return this.properties; + } + + /** + * Set vCenter related data. + * + * @param properties the properties value to set + * @return the VCenterInner object itself. + */ + public VCenterInner withProperties(VCenterProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the VCenterInner object itself. + */ + public VCenterInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VaultHealthDetailsImpl.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VaultHealthDetailsImpl.java new file mode 100644 index 0000000000000..7e7ac40949e9c --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VaultHealthDetailsImpl.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.VaultHealthDetails; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.VaultHealthProperties; + +class VaultHealthDetailsImpl extends WrapperImpl implements VaultHealthDetails { + private final RecoveryServicesManager manager; + VaultHealthDetailsImpl(VaultHealthDetailsInner inner, RecoveryServicesManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public RecoveryServicesManager manager() { + return this.manager; + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public VaultHealthProperties properties() { + return this.inner().properties(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VaultHealthDetailsInner.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VaultHealthDetailsInner.java new file mode 100644 index 0000000000000..b1c758f52be37 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/VaultHealthDetailsInner.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; + +import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.VaultHealthProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.ProxyResource; + +/** + * Vault health details definition. + */ +public class VaultHealthDetailsInner extends ProxyResource { + /** + * The vault health related data. + */ + @JsonProperty(value = "properties") + private VaultHealthProperties properties; + + /** + * Resource Location. + */ + @JsonProperty(value = "location") + private String location; + + /** + * Get the vault health related data. + * + * @return the properties value + */ + public VaultHealthProperties properties() { + return this.properties; + } + + /** + * Set the vault health related data. + * + * @param properties the properties value to set + * @return the VaultHealthDetailsInner object itself. + */ + public VaultHealthDetailsInner withProperties(VaultHealthProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get resource Location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource Location. + * + * @param location the location value to set + * @return the VaultHealthDetailsInner object itself. + */ + public VaultHealthDetailsInner withLocation(String location) { + this.location = location; + return this; + } + +} diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/package-info.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/package-info.java new file mode 100644 index 0000000000000..12e976d958486 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/implementation/package-info.java @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the implementation classes for SiteRecoveryManagementClient. + */ +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation; diff --git a/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/package-info.java b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/package-info.java new file mode 100644 index 0000000000000..507520184bab7 --- /dev/null +++ b/recoveryservices.siterecovery/resource-manager/v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/package-info.java @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the classes for SiteRecoveryManagementClient. + */ +package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10; From dda50251c3c07b5086b28a126560970d9db234fd Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 08:55:42 -0700 Subject: [PATCH 079/147] update azure=arm-client-runtime test jar dependency (#4232) --- notificationhubs/resource-manager/v2016_03_01/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/notificationhubs/resource-manager/v2016_03_01/pom.xml b/notificationhubs/resource-manager/v2016_03_01/pom.xml index 61c69279d5cda..ff98ac0d32bc0 100644 --- a/notificationhubs/resource-manager/v2016_03_01/pom.xml +++ b/notificationhubs/resource-manager/v2016_03_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5
From 11779a1b5cccd82b8ba3d7af94bed9fe7ec2aad5 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 10:25:02 -0700 Subject: [PATCH 080/147] update azure-arm-client-runtime test jar dependency (#4252) --- relay/resource-manager/v2017_04_01/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/relay/resource-manager/v2017_04_01/pom.xml b/relay/resource-manager/v2017_04_01/pom.xml index ae40ed2b2f1c3..c0339025f1b5c 100644 --- a/relay/resource-manager/v2017_04_01/pom.xml +++ b/relay/resource-manager/v2017_04_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5
From cdd91bd1be1ede06ef69b37ea147458d68f4a5b4 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 10:31:46 -0700 Subject: [PATCH 081/147] Authorization: update azure-arm-client-runtime test jar dependency (#4259) * update azure-arm-client-runtime test jar dependency * Update pom.xml --- authorization/resource-manager/v2015_06_01/pom.xml | 2 ++ authorization/resource-manager/v2018_09_01_preview/pom.xml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/authorization/resource-manager/v2015_06_01/pom.xml b/authorization/resource-manager/v2015_06_01/pom.xml index deb7668262fb2..e19beddcc02bf 100644 --- a/authorization/resource-manager/v2015_06_01/pom.xml +++ b/authorization/resource-manager/v2015_06_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5
diff --git a/authorization/resource-manager/v2018_09_01_preview/pom.xml b/authorization/resource-manager/v2018_09_01_preview/pom.xml index 7fdb6a3da763f..eb6c3404737f0 100644 --- a/authorization/resource-manager/v2018_09_01_preview/pom.xml +++ b/authorization/resource-manager/v2018_09_01_preview/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5
From 936a1cd63db9a73c8a681365475fe158437bfd86 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:10:34 -0700 Subject: [PATCH 082/147] Resource Health: update azure-arm-client-runtime test jar dependency (#4253) * update azure-arm-client-runtime test jar dependency * update azure-arm-client-runtime test jar dependency --- resourcehealth/resource-manager/v2015_01_01/pom.xml | 2 ++ resourcehealth/resource-manager/v2017_07_01/pom.xml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/resourcehealth/resource-manager/v2015_01_01/pom.xml b/resourcehealth/resource-manager/v2015_01_01/pom.xml index b35fcde154c64..1baf0aa38a317 100644 --- a/resourcehealth/resource-manager/v2015_01_01/pom.xml +++ b/resourcehealth/resource-manager/v2015_01_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 diff --git a/resourcehealth/resource-manager/v2017_07_01/pom.xml b/resourcehealth/resource-manager/v2017_07_01/pom.xml index 58d389a738ce3..6c7701b4d0419 100644 --- a/resourcehealth/resource-manager/v2017_07_01/pom.xml +++ b/resourcehealth/resource-manager/v2017_07_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 946f82108e75b527d6121f1289f86906b9c3c970 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:11:51 -0700 Subject: [PATCH 083/147] update azure-arm-client-runtime test jar dependency (#4255) --- resources/resource-manager/v2016_09_01/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/resources/resource-manager/v2016_09_01/pom.xml b/resources/resource-manager/v2016_09_01/pom.xml index 0fa6698b6ff77..59b942d2fc758 100644 --- a/resources/resource-manager/v2016_09_01/pom.xml +++ b/resources/resource-manager/v2016_09_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 9da9806e304632e90237cf644d0b2bfc9c110d63 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:12:57 -0700 Subject: [PATCH 084/147] Service Bus: update azure-arm-client-runtime test jar dependency (#4257) * update azure-arm-client-runtime test jar dependency * update azure-arm-client-runtime test jar dependency --- servicebus/resource-manager/v2015_08_01/pom.xml | 2 ++ servicebus/resource-manager/v2018_01_01_preview/pom.xml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/servicebus/resource-manager/v2015_08_01/pom.xml b/servicebus/resource-manager/v2015_08_01/pom.xml index 77d52c2ea066f..6c4421ae3e797 100644 --- a/servicebus/resource-manager/v2015_08_01/pom.xml +++ b/servicebus/resource-manager/v2015_08_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 diff --git a/servicebus/resource-manager/v2018_01_01_preview/pom.xml b/servicebus/resource-manager/v2018_01_01_preview/pom.xml index 5fd8887577830..68c64ab067a81 100644 --- a/servicebus/resource-manager/v2018_01_01_preview/pom.xml +++ b/servicebus/resource-manager/v2018_01_01_preview/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From a51db8ae32732ac5f840613f734ff37cde6742e7 Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:14:57 -0700 Subject: [PATCH 085/147] update azure-arm-client-runtime test jar dependency (#4258) --- servicefabric/resource-manager/v2018_02_01/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/servicefabric/resource-manager/v2018_02_01/pom.xml b/servicefabric/resource-manager/v2018_02_01/pom.xml index f711362b446c0..a8bbdaaca20e3 100644 --- a/servicefabric/resource-manager/v2018_02_01/pom.xml +++ b/servicefabric/resource-manager/v2018_02_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 94a64ebccf898a848cbd5dbb2cf4c011e856103f Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:15:54 -0700 Subject: [PATCH 086/147] update azure-arm-client-runtime test jar dependency (#4261) --- mediaservices/resource-manager/v2015_10_01/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/mediaservices/resource-manager/v2015_10_01/pom.xml b/mediaservices/resource-manager/v2015_10_01/pom.xml index f5b4359736385..70a748016da39 100644 --- a/mediaservices/resource-manager/v2015_10_01/pom.xml +++ b/mediaservices/resource-manager/v2015_10_01/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From a9b05a14f184a980b077903bac2f42b2cee4053d Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 11:32:26 -0700 Subject: [PATCH 087/147] update azure-arm-client-runtime test jar dependency (#4264) --- authorization/resource-manager/v2018_07_01_preview/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/authorization/resource-manager/v2018_07_01_preview/pom.xml b/authorization/resource-manager/v2018_07_01_preview/pom.xml index 3a6fcf1ee50e0..e29abe1d0dff8 100644 --- a/authorization/resource-manager/v2018_07_01_preview/pom.xml +++ b/authorization/resource-manager/v2018_07_01_preview/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 6b0efe2590c4be8065cb34512b41c9dcf25cc986 Mon Sep 17 00:00:00 2001 From: bsiegel <96068+bsiegel@users.noreply.github.com> Date: Wed, 3 Jul 2019 12:23:40 -0700 Subject: [PATCH 088/147] Apply tag to scheduled builds (#4238) --- eng/pipelines/templates/jobs/archetype-sdk-client.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/eng/pipelines/templates/jobs/archetype-sdk-client.yml b/eng/pipelines/templates/jobs/archetype-sdk-client.yml index cd3aece496be9..bafa2cf2cf373 100644 --- a/eng/pipelines/templates/jobs/archetype-sdk-client.yml +++ b/eng/pipelines/templates/jobs/archetype-sdk-client.yml @@ -19,6 +19,11 @@ jobs: JavaVersion: '1.11' steps: + - script: | + echo "##vso[build.addbuildtag]Scheduled" + displayName: 'Tag scheduled builds' + condition: and(eq(variables['Build.SourceBranchName'],'master'),eq(variables['Build.Reason'],'Schedule')) + - task: Maven@3 displayName: 'Build and Package' inputs: @@ -212,4 +217,4 @@ jobs: condition: succeededOrFailed() inputs: mergeTestResults: true - testRunTitle: '$(OSName) on Java $(JavaVersion)' \ No newline at end of file + testRunTitle: '$(OSName) on Java $(JavaVersion)' From 53c6808a03ab038ac4f0cf5b527eafd02128bbe9 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Wed, 3 Jul 2019 13:14:07 -0700 Subject: [PATCH 089/147] Setup basic elements for identity ci. (#4267) --- sdk/identity/ci.yml | 23 +++++++++++++++++++++++ sdk/identity/pom.service.xml | 16 ++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 sdk/identity/ci.yml create mode 100644 sdk/identity/pom.service.xml diff --git a/sdk/identity/ci.yml b/sdk/identity/ci.yml new file mode 100644 index 0000000000000..ae4d32447fdfd --- /dev/null +++ b/sdk/identity/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/identity/ + +pr: + branches: + include: + - master + paths: + include: + - sdk/identity/ + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: identity \ No newline at end of file diff --git a/sdk/identity/pom.service.xml b/sdk/identity/pom.service.xml new file mode 100644 index 0000000000000..2de621745de56 --- /dev/null +++ b/sdk/identity/pom.service.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + com.azure + azure-identity-service + pom + 1.0.0 + + + + From 7d44c0c6c6142fe8321b13e602bb426c18e0756d Mon Sep 17 00:00:00 2001 From: iscai-msft <43154838+iscai-msft@users.noreply.github.com> Date: Wed, 3 Jul 2019 13:23:03 -0700 Subject: [PATCH 090/147] update azure-arm-client-runtime test jar dependency (#4256) --- search/resource-manager/v2015_02_28/pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/search/resource-manager/v2015_02_28/pom.xml b/search/resource-manager/v2015_02_28/pom.xml index c09be0fa76d5a..19f7e0c74beeb 100644 --- a/search/resource-manager/v2015_02_28/pom.xml +++ b/search/resource-manager/v2015_02_28/pom.xml @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 From 6dc2430f288cffcc715c4dcce7e866ef5b9bf5a5 Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Wed, 3 Jul 2019 13:55:48 -0700 Subject: [PATCH 091/147] Update checkstyle suppressions (#4268) * Add null check for crv. * Update checkstyle suppressions to use correct paths. --- .../main/resources/checkstyle/checkstyle-suppressions.xml | 6 +++--- .../com/microsoft/azure/keyvault/webkey/JsonWebKey.java | 5 ++++- 2 files changed, 7 insertions(+), 4 deletions(-) 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 f8a5f76638da4..09da6af09b39e 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 @@ -6,13 +6,13 @@ - + + files="keyvault[/\\]microsoft-azure-.*[/\\].*[/\\](IKey|ISignatureTransform|KeyVaultClientBase|KeyVaultClientCustom)\.java"/> - + diff --git a/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java index bece713ef94a9..097fefdeb5b4b 100644 --- a/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java +++ b/sdk/keyvault/microsoft-azure-keyvault-webkey/src/main/java/com/microsoft/azure/keyvault/webkey/JsonWebKey.java @@ -1154,7 +1154,10 @@ public int hashCode() { } else if (JsonWebKeyType.EC.equals(kty)) { hashCode += hashCode(x); hashCode += hashCode(y); - hashCode += crv.hashCode(); + + if (crv != null) { + hashCode += crv.hashCode(); + } } else if (JsonWebKeyType.RSA_HSM.equals(kty) || JsonWebKeyType.EC_HSM.equals(kty)) { hashCode += hashCode(t); } From d2fa73440612e365034fc91a2a533382c0280598 Mon Sep 17 00:00:00 2001 From: Jonathan Giles Date: Thu, 4 Jul 2019 10:18:15 +1200 Subject: [PATCH 092/147] Update root readme (#4247) Updating readme.md to follow consistent template specified for all languages --- README.md | 197 +++++++++++++++--------------------------------------- 1 file changed, 54 insertions(+), 143 deletions(-) diff --git a/README.md b/README.md index 27b268ef33dac..a148334fe29d8 100644 --- a/README.md +++ b/README.md @@ -1,145 +1,56 @@ -> :warning: *NOTE: The **Azure Libraries for Java** project (resource management APIs with fluent interface design pattern) has moved to http://github.com/azure/azure-libraries-for-java, so please log issues for that project in that new repository. This repository is now dedicated to other, auto-generated, non-management Azure SDKs only.* - -# Azure SDKs for Java - -| Component | Build Status | -| --------- | ------------ | -| Management Libraries | [![Build Status](https://travis-ci.org/Azure/azure-sdk-for-java.svg?branch=master)](https://travis-ci.org/Azure/azure-sdk-for-java) | -| Client Libraries | [![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/17?branchName=master)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=17)
[![Build Documentation](https://img.shields.io/badge/documentation-published-blue.svg)](https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java/index.html)| - -:+1: [Try Azure for FREE](http://go.microsoft.com/fwlink/?LinkId=330212) - -This repository contains Azure SDKs enabling the programmatic *consumption* of miscellaneous Azure services (i.e. *not management* - for that see http://github.com/azure/azure-libraries-for-java) - -Currently, this repository contains the following Azure SDKs: - -* [Media Services](#media-services) -* [Cognitive Services](#cognitive-services) - * [Search](#search) - * [Entity Search](#entity-search) - * [Language](#language) - * [Text Analytics](#text-analytics) - * [Vision](#vision) - * [Face API](#face-api) -* [Azure Event Grid](#azure-event-grid) - -## Other Azure SDKs - -These other Azure SDKs for Java, that are not currently in this repository, can be found as follows: - -* [Azure ActiveDirectory Authentication Library (ADAL)](https://github.com/AzureAD/azure-activedirectory-library-for-java) -* [Azure Batch SDK for Java](https://github.com/azure/azure-batch-sdk-for-java) -* [Azure Data Lake Store Client for Java](https://github.com/Azure/azure-data-lake-store-java) -* [Azure DocumentDB (CosmosDB) SDK for Java](https://github.com/Azure/azure-documentdb-java) -* [Azure CosmosDB Async SDK for Java](https://github.com/Azure/azure-cosmosdb-java) -* [Azure Key Vault SDK for Java](https://github.com/Azure/azure-keyvault-java) -* [Azure Service Bus SDK for Java](https://github.com/Azure/azure-service-bus-java) -* [Azure Storage SDK for Java](https://github.com/Azure/azure-storage-java) -* [Azure Storage SDK Async for Java](https://github.com/Azure/azure-storage-java-async) -* [Azure Functions SDK for Java](https://github.com/Azure/azure-functions-java-worker) -* [Azure IoT SDK for Java](https://github.com/Azure/azure-iot-sdk-java) -* [Azure Event Hub SDK for Java]() -* [Azure Notification Hubs for Java](https://github.com/Azure/azure-notificationhubs-java-backend) -* [Azure Management Libraries for Java](https://github.com/azure/azure-libraries-for-java) - -Other libraries: -* [Microsoft JDBC Driver for SQL Server](https://github.com/Microsoft/mssql-jdbc) - -## General Information -* [Prerequisites](#prerequisites) -* [Help and issues](#help-and-issues) -* [Contribute code](#contribute-code) - -## Cognitive Services - -The following projects provide Java APIs for [Azure Cognitive Services](https://azure.microsoft.com/en-us/services/cognitive-services/), empowering your applications with intelligent algorithms that enable them to see, hear, speak and understand. - -* *Language* - * **Spell Check** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-spellcheck) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-spellcheck%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/BingSearchV7)| [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3ASpellCheck) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/spell-check/) | - | --- | --- | --- | --- | --- | - * **Text Analytics** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-textanalytics) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-language%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/TextAnalytics) | [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3ATextAnalytics) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/text-analytics/) | - | --- | --- | --- | --- | --- | - -* *Search* - * **Custom Search** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-customsearch) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-customsearch%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/BingSearchV7)| [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3ACustomSearch) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/bing-custom-search-api/) | - | --- | --- | --- | --- | --- | - * **Entity Search** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-entitysearch) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-entitysearch%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/BingSearchV7)| [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AEntitySearch) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/bing-entity-search-api/) | - | --- | --- | --- | --- | --- | - * **Image Search** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-imagesearch) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-imagesearch%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/BingSearchV7)| [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AImageSearch) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/bing-image-search-api/) | - | --- | --- | --- | --- | --- | - * **News Search** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-newssearch) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-newssearch%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/BingSearchV7)| [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3ANewsSearch) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/bing-news-search-api/) | - | --- | --- | --- | --- | --- | - * **Video Search** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-videosearch) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-videosearch%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/BingSearchV7)| [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AVideoSearch) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/bing-video-search-api/) | - | --- | --- | --- | --- | --- | - * **Web Search** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-websearch) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-websearch%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/BingSearchV7) | [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AWebSearch) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/bing-web-search-api/) | - | --- | --- | --- | --- | --- | - -* *Vision* - * **Computer Vision** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-computervision) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-computervision%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/ComputerVision) | [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AComputerVision) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision) | - | --- | --- | --- | --- | --- | - * **Content Moderator** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-contentmoderator) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-cognitiveservices-contentmoderator%22) | [:pencil: Samples](https://github.com/Azure-Samples/cognitive-services-java-sdk-samples/tree/master/ContentModerator) | [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AContentModerator) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/content-moderator) | - | --- | --- | --- | --- | --- | - * **Face API** - - | [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/cognitiveservices/azure-vision) | [:arrow_down: Download](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22azure-faceapi%22) | :pencil: Samples | [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AFaceAPI) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/cognitive-services/face/) | - | --- | --- | --- | --- | --- | - -## Media Services - -This project provides Java APIs for Azure Media Services, enabling you to share media content through premium video workflows: - -| [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/0.9/services/azure-media) | [:arrow_down: Download](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.microsoft.azure%22%20AND%20a%3A%22azure-media%22) | [:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AMediaServices) | [:book: Learn more...](https://azure.microsoft.com/en-us/services/media-services/) | -| --- | --- | --- | --- | - -## Azure Event Grid - -This project provides Java APIs for [Azure Event Grid](https://azure.com/eventgrid), enabling you to build reactive programs and applications in the cloud: - -| [:page_facing_up: Sources...](https://github.com/Azure/azure-sdk-for-java/tree/master/azure-eventgrid) | :arrow_down: Download | :pencil: Samples |[:triangular_flag_on_post: Issues](https://github.com/azure/azure-sdk-for-java/issues?q=is%3Aopen+is%3Aissue+label%3AEventGrid) | [:book: Learn more...](https://azure.microsoft.com/services/event-grid/) | -| --- | --- | --- | --- | --- | - -## Prerequisites - -- A Java Developer Kit (JDK), v 1.7 or later -- Maven - -## Help and Issues - -If you encounter any bugs with these SDKs, please file issues via [Issues](https://github.com/Azure/azure-sdk-for-java/issues) or checkout [StackOverflow for Azure Java SDK](http://stackoverflow.com/questions/tagged/azure-java-sdk). - -## Contribute Code - -If you would like to become an active contributor to this project please follow the instructions provided in [Microsoft Azure Projects Contribution Guidelines](http://azure.github.io/guidelines.html). - -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Add some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request - ---- - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. +# Azure SDK for Java +[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/17?branchName=master)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=17) [![Build Documentation](https://img.shields.io/badge/documentation-published-blue.svg)](https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java/index.html) [![Dependencies](https://img.shields.io/badge/dependencies-analyzed-blue.svg)](https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java/staging/dependencies.html) [![SpotBugs](https://img.shields.io/badge/SpotBugs-Clean-success.svg)](https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java/staging/spotbugsXml.html) [![CheckStyle](https://img.shields.io/badge/CheckStyle-Clean-success.svg)](https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java/staging/checkstyle-aggregate.html) -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2FREADME.png) + +This repository contains official Java libraries for Azure services. For reference documentation go to [Azure SDK for Java documentation](http://aka.ms/java-docs), and tutorials, samples, quick starts and other documentation, go to [Azure for Java Developers](https://docs.microsoft.com/java/azure/). + +You can find a complete list of all the packages for these libraries [here](packages.md). + +## Getting started + +To get started with a specific library, see the **README.md** file located in the library's project folder. You can find service libraries in the `/sdk` directory. + +For tutorials, samples, quick starts and other documentation, visit [Azure for Java Developers](https://docs.microsoft.com/java/azure/). + +### Prerequisites +Java 8 or later is required to use the July 2019 client preview libraries, otherwise Java 7 or later is required. + +## Packages available +Each service might have a number of libraries available from each of the following categories: + +* [Client - July 2019 Preview](#Client-July-2019-Preview) +* [Client - Stable](#Client-Stable) +* [Management](#Management) + +### Client: July 2019 Preview +New wave of packages that we are currently releasing in **preview**. These libraries follow the [Azure SDK Design Guidelines for Java](https://azuresdkspecs.z5.web.core.windows.net/JavaSpec.html) and share a number of core features such as HTTP retries, logging, transport protocols, authentication protocols, etc., so that once you learn how to use these features in one client library, you will know how to use them in other client libraries. You can learn about these shared features [here](core). + +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) +- [Key Vault Keys](keyvault/client/keys/README.md) +- [Key Vault Secrets](keyvault/client/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. + +### Client: Stable +Last stable versions of packages that have been provided for usage with Azure and are production-ready. These libraries provide similar functionalities to the preview libraries, as they allow you to use and consume existing resources and interact with them, for example: upload a blob. Stable library directories start with `microsoft-azure-`, e.g. `microsoft-azure-keyvault`. + +### Management +Libraries which enable you to provision specific resources. They are responsible for directly mirroring and consuming Azure service's REST endpoints. Management library directories contain `-mgmt-`, e.g. `azure-mgmt-keyvault`. + +## Need help? +* For reference documentation visit the [Azure SDK for Java documentation](http://aka.ms/java-docs). +* For tutorials, samples, quick starts and other documentation, visit [Azure for Java Developers](https://docs.microsoft.com/java/azure/). +* For build reports on code quality, test coverage, etc, visit [Azure Java SDK](https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java/index.html). +* File an issue via [Github Issues](https://github.com/Azure/azure-sdk-for-java/issues/new/choose). +* Check [previous questions](https://stackoverflow.com/questions/tagged/azure-java-sdk) or ask new ones on StackOverflow using `azure-java-sdk` tag. + +## Contributing +For details on contributing to this repository, see the [contributing guide](CONTRIBUTING.md). + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2FREADME.png) \ No newline at end of file From b4ae079186118db5b4695ab28b42b6f48bbdec62 Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Wed, 3 Jul 2019 15:51:49 -0700 Subject: [PATCH 093/147] Fix sample spotbugs (#4275) * Fix illegalargument when sending with boolean * Fix spotbugs issue where \n is used rather than %n. --- .../java/ConsumeEventsFromKnownSequenceNumberPosition.java | 2 +- .../azure-eventhubs/src/samples/java/GetEventHubMetadata.java | 2 +- .../src/samples/java/PublishEventsWithCustomMetadata.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java b/eventhubs/client/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java index 3f779a1c815da..aa1dfa9fcb95f 100644 --- a/eventhubs/client/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java +++ b/eventhubs/client/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java @@ -66,7 +66,7 @@ public static void main(String[] args) throws InterruptedException, IOException System.out.println("Waiting for partition properties to complete..."); // Acquiring the semaphore so that this sample does not end before all the partition properties are fetched. semaphore.acquire(); - System.out.printf("Last enqueued sequence number: %s\n", lastEnqueuedSequenceNumber); + System.out.printf("Last enqueued sequence number: %s%n", lastEnqueuedSequenceNumber); // Make sure to have at least one non-empty event hub in order to continue the sample execution // if you don't have an non-empty event hub, try with another example 'SendEvent' in the same directory. diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/GetEventHubMetadata.java b/eventhubs/client/azure-eventhubs/src/samples/java/GetEventHubMetadata.java index 4716982af8eb2..f81a400160d4b 100644 --- a/eventhubs/client/azure-eventhubs/src/samples/java/GetEventHubMetadata.java +++ b/eventhubs/client/azure-eventhubs/src/samples/java/GetEventHubMetadata.java @@ -41,7 +41,7 @@ public static void main(String[] args) throws InterruptedException { System.out.println("The Event Hub has the following properties:"); System.out.printf( "Event Hub Name: %s; Partition Id: %s; Is partition empty? %s; First Sequence Number: %s; " - + "Last Enqueued Time: %s; Last Enqueued Sequence Number: %s; Last Enqueued Offset: %s \n", + + "Last Enqueued Time: %s; Last Enqueued Sequence Number: %s; Last Enqueued Offset: %s", properties.eventHubPath(), properties.id(), properties.isEmpty(), properties.beginningSequenceNumber(), properties.lastEnqueuedTime(), diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java b/eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java index ffed26869db69..e71a36f597936 100644 --- a/eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java +++ b/eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java @@ -61,7 +61,7 @@ public static void main(String[] args) { EventData secEvent = new EventData("EventData Sample 2".getBytes(UTF_8)); secEvent.properties().put("EventType", "com.microsoft.samples.goodbye-event"); secEvent.properties().put("priority", "17"); - secEvent.properties().put("blob", true); + secEvent.properties().put("blob", 10); final Flux data = Flux.just(firstEvent, secEvent); From b8342552d080e0b4d34916e3a09816e764d8f9c1 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Wed, 3 Jul 2019 16:00:27 -0700 Subject: [PATCH 094/147] Setup CI files for loganalytics. (#4278) --- sdk/loganalytics/ci.yml | 23 +++++++++++++++++++++++ sdk/loganalytics/pom.service.xml | 16 ++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 sdk/loganalytics/ci.yml create mode 100644 sdk/loganalytics/pom.service.xml diff --git a/sdk/loganalytics/ci.yml b/sdk/loganalytics/ci.yml new file mode 100644 index 0000000000000..a115776c40a5e --- /dev/null +++ b/sdk/loganalytics/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/loganalytics/ + +pr: + branches: + include: + - master + paths: + include: + - sdk/loganalytics/ + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: loganalytics \ No newline at end of file diff --git a/sdk/loganalytics/pom.service.xml b/sdk/loganalytics/pom.service.xml new file mode 100644 index 0000000000000..e923187fcbcac --- /dev/null +++ b/sdk/loganalytics/pom.service.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + com.azure + azure-loganalytics-service + pom + 1.0.0 + + + + From 85de396246e4c01a9d79d7bc17f1090c08a726b2 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Wed, 3 Jul 2019 17:53:19 -0700 Subject: [PATCH 095/147] Move identity to sdk/identity (#4271) * Base move. * Updated POMs. * Fixed pom.client.xml * Fixed up POM reference. --- pom.client.xml | 2 +- {identity/client => sdk/identity/azure-identity}/pom.xml | 2 +- .../src/main/java/com/azure/identity/IdentityClient.java | 0 .../main/java/com/azure/identity/IdentityClientOptions.java | 0 .../java/com/azure/identity/credential/AadCredential.java | 0 .../azure/identity/credential/AppServiceMSICredential.java | 0 .../com/azure/identity/credential/ChainedTokenCredential.java | 0 .../identity/credential/ClientCertificateCredential.java | 0 .../com/azure/identity/credential/ClientSecretCredential.java | 0 .../com/azure/identity/credential/DefaultAzureCredential.java | 0 .../com/azure/identity/credential/EnvironmentCredential.java | 0 .../azure/identity/credential/ManagedIdentityCredential.java | 0 .../identity/credential/VirtualMachineMSICredential.java | 0 .../main/java/com/azure/identity/credential/package-info.java | 0 .../main/java/com/azure/identity/implementation/MSIToken.java | 0 .../com/azure/identity/implementation/util/Adal4jUtil.java | 0 .../src/main/java/com/azure/identity/package-info.java | 0 .../java/com/azure/identity/EnvironmentCredentialTests.java | 0 .../com/azure/identity/ManagedIdentityCredentialTests.java | 0 sdk/identity/pom.service.xml | 4 +--- 20 files changed, 3 insertions(+), 5 deletions(-) rename {identity/client => sdk/identity/azure-identity}/pom.xml (94%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/IdentityClient.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/IdentityClientOptions.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/AadCredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/AppServiceMSICredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/ChainedTokenCredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/ClientCertificateCredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/ClientSecretCredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/DefaultAzureCredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/EnvironmentCredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/ManagedIdentityCredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/VirtualMachineMSICredential.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/credential/package-info.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/implementation/MSIToken.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/implementation/util/Adal4jUtil.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/main/java/com/azure/identity/package-info.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/test/java/com/azure/identity/EnvironmentCredentialTests.java (100%) rename {identity/client => sdk/identity/azure-identity}/src/test/java/com/azure/identity/ManagedIdentityCredentialTests.java (100%) diff --git a/pom.client.xml b/pom.client.xml index 8455e01021213..a5b5a6c31a388 100644 --- a/pom.client.xml +++ b/pom.client.xml @@ -703,6 +703,6 @@ ./eventhubs/client ./keyvault/client ./sdk/tracing - ./identity/client + ./sdk/identity/azure-identity diff --git a/identity/client/pom.xml b/sdk/identity/azure-identity/pom.xml similarity index 94% rename from identity/client/pom.xml rename to sdk/identity/azure-identity/pom.xml index 64ccae2bceccc..1985a9c043a7c 100644 --- a/identity/client/pom.xml +++ b/sdk/identity/azure-identity/pom.xml @@ -12,7 +12,7 @@ com.azure azure-client-sdk-parent 1.0.0 - ../../pom.client.xml + ../../../pom.client.xml diff --git a/identity/client/src/main/java/com/azure/identity/IdentityClient.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/IdentityClient.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/IdentityClient.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/IdentityClient.java diff --git a/identity/client/src/main/java/com/azure/identity/IdentityClientOptions.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/IdentityClientOptions.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/IdentityClientOptions.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/IdentityClientOptions.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/AadCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/AadCredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/AadCredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/AadCredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/AppServiceMSICredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/AppServiceMSICredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/AppServiceMSICredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/AppServiceMSICredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/ChainedTokenCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/ChainedTokenCredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/ChainedTokenCredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/ChainedTokenCredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/ClientCertificateCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/ClientCertificateCredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/ClientCertificateCredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/ClientCertificateCredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/ClientSecretCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/ClientSecretCredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/ClientSecretCredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/ClientSecretCredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/DefaultAzureCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/DefaultAzureCredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/DefaultAzureCredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/DefaultAzureCredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/EnvironmentCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/EnvironmentCredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/EnvironmentCredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/EnvironmentCredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/ManagedIdentityCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/ManagedIdentityCredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/ManagedIdentityCredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/ManagedIdentityCredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/VirtualMachineMSICredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/VirtualMachineMSICredential.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/VirtualMachineMSICredential.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/VirtualMachineMSICredential.java diff --git a/identity/client/src/main/java/com/azure/identity/credential/package-info.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/package-info.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/credential/package-info.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/credential/package-info.java diff --git a/identity/client/src/main/java/com/azure/identity/implementation/MSIToken.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/MSIToken.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/implementation/MSIToken.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/MSIToken.java diff --git a/identity/client/src/main/java/com/azure/identity/implementation/util/Adal4jUtil.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/util/Adal4jUtil.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/implementation/util/Adal4jUtil.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/util/Adal4jUtil.java diff --git a/identity/client/src/main/java/com/azure/identity/package-info.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/package-info.java similarity index 100% rename from identity/client/src/main/java/com/azure/identity/package-info.java rename to sdk/identity/azure-identity/src/main/java/com/azure/identity/package-info.java diff --git a/identity/client/src/test/java/com/azure/identity/EnvironmentCredentialTests.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/EnvironmentCredentialTests.java similarity index 100% rename from identity/client/src/test/java/com/azure/identity/EnvironmentCredentialTests.java rename to sdk/identity/azure-identity/src/test/java/com/azure/identity/EnvironmentCredentialTests.java diff --git a/identity/client/src/test/java/com/azure/identity/ManagedIdentityCredentialTests.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/ManagedIdentityCredentialTests.java similarity index 100% rename from identity/client/src/test/java/com/azure/identity/ManagedIdentityCredentialTests.java rename to sdk/identity/azure-identity/src/test/java/com/azure/identity/ManagedIdentityCredentialTests.java diff --git a/sdk/identity/pom.service.xml b/sdk/identity/pom.service.xml index 2de621745de56..6b09f2a0921b2 100644 --- a/sdk/identity/pom.service.xml +++ b/sdk/identity/pom.service.xml @@ -9,8 +9,6 @@ pom 1.0.0 - + azure-identity From e76ce7a2e64dbe602782fbc0f8e43020e55e4ab8 Mon Sep 17 00:00:00 2001 From: Jonathan Giles Date: Thu, 4 Jul 2019 16:21:13 +1200 Subject: [PATCH 096/147] Update README.md (#4282) Updating links and text to replace 'common' with 'core', and update version number in maven dependency text. --- core/azure-core-test/README.md | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/core/azure-core-test/README.md b/core/azure-core-test/README.md index b84ede075f345..9fbc3c45c3f64 100644 --- a/core/azure-core-test/README.md +++ b/core/azure-core-test/README.md @@ -1,6 +1,6 @@ -# Azure common test client library for Java +# Azure core test client library for Java -Library containing common classes used to test Azure SDK client libraries. +Library containing core classes used to test Azure SDK client libraries. * Create live or playback JUnit tests using [TestBase][TestBase.java] and leveraging [InterceptorManager][InterceptorManager.java] to keep track of @@ -13,11 +13,11 @@ Library containing common classes used to test Azure SDK client libraries. To use this package, add the following to your _pom.xml_. ```xml - - com.azure - azure-common-test - 1.0.0-SNAPSHOT - + + com.azure + azure-core-test + 1.0.0-preview.1 + ``` ## Key concepts @@ -98,8 +98,7 @@ If you encounter any bugs with these SDKs, please file issues via ## Next steps Other useful packages are: -* [azure-common](../azure-common): Contains common classes and functionality used by all client libraries. -* [azure-common-auth](../azure-common-auth): Contains common classes for authenticating with Azure. +* [azure-core](../azure-core): Contains core classes and functionality used by all client libraries. ## Contributing @@ -112,8 +111,8 @@ If you would like to become an active contributor to this project please follow 1. Push to the branch (`git push origin my-new-feature`) 1. Create new Pull Request -[InterceptorManager.java]: ./src/main/java/com/azure/common/test/InterceptorManager.java -[PlaybackClient.java]: ./src/main/java/com/azure/common/test/http/PlaybackClient.java -[RecordedData.java]: ./src/main/java/com/azure/common/test/models/RecordedData.java -[RecordNetworkCallPolicy.java]: ./src/main/java/com/azure/common/test/policy/RecordNetworkCallPolicy.java -[TestBase.java]: ./src/main/java/com/azure/common/test/TestBase.java +[InterceptorManager.java]: ./src/main/java/com/azure/core/test/InterceptorManager.java +[PlaybackClient.java]: ./src/main/java/com/azure/core/test/http/PlaybackClient.java +[RecordedData.java]: ./src/main/java/com/azure/core/test/models/RecordedData.java +[RecordNetworkCallPolicy.java]: ./src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java +[TestBase.java]: ./src/main/java/com/azure/core/test/TestBase.java From 8aea91b998c94d0c1dbfd4a2e5afc2b0cce12846 Mon Sep 17 00:00:00 2001 From: Vinay Gera Date: Thu, 4 Jul 2019 16:22:26 -0700 Subject: [PATCH 097/147] samples update (#4285) --- .../keys/BackupAndRestoreOperations.java | 3 +-- .../keys/BackupAndRestoreOperationsAsync.java | 7 +++--- .../security/keyvault}/keys/HelloWorld.java | 3 +-- .../keyvault}/keys/HelloWorldAsync.java | 15 ++++++------ .../keyvault}/keys/ListOperations.java | 3 +-- .../keyvault}/keys/ListOperationsAsync.java | 13 +++++------ .../keyvault}/keys/ManagingDeletedKeys.java | 5 ++-- .../keys/ManagingDeletedKeysAsync.java | 15 ++++++------ .../secrets/BackupAndRestoreOperations.java | 3 +-- .../BackupAndRestoreOperationsAsync.java | 13 +++++------ .../keyvault}/secrets/HelloWorld.java | 3 +-- .../keyvault}/secrets/HelloWorldAsync.java | 23 +++++++++---------- .../keyvault}/secrets/ListOperations.java | 3 +-- .../secrets/ListOperationsAsync.java | 12 +++++----- .../secrets/ManagingDeletedSecrets.java | 5 ++-- .../secrets/ManagingDeletedSecretsAsync.java | 15 ++++++------ .../SecretClientJavaDocCodeSnippets.java | 2 +- 17 files changed, 64 insertions(+), 79 deletions(-) rename keyvault/client/keys/src/samples/java/{ => com/azure/security/keyvault}/keys/BackupAndRestoreOperations.java (98%) rename keyvault/client/keys/src/samples/java/{ => com/azure/security/keyvault}/keys/BackupAndRestoreOperationsAsync.java (94%) rename keyvault/client/keys/src/samples/java/{ => com/azure/security/keyvault}/keys/HelloWorld.java (98%) rename keyvault/client/keys/src/samples/java/{ => com/azure/security/keyvault}/keys/HelloWorldAsync.java (88%) rename keyvault/client/keys/src/samples/java/{ => com/azure/security/keyvault}/keys/ListOperations.java (98%) rename keyvault/client/keys/src/samples/java/{ => com/azure/security/keyvault}/keys/ListOperationsAsync.java (89%) rename keyvault/client/keys/src/samples/java/{ => com/azure/security/keyvault}/keys/ManagingDeletedKeys.java (96%) rename keyvault/client/keys/src/samples/java/{ => com/azure/security/keyvault}/keys/ManagingDeletedKeysAsync.java (87%) rename keyvault/client/secrets/src/samples/java/{ => com/azure/security/keyvault}/secrets/BackupAndRestoreOperations.java (97%) rename keyvault/client/secrets/src/samples/java/{ => com/azure/security/keyvault}/secrets/BackupAndRestoreOperationsAsync.java (88%) rename keyvault/client/secrets/src/samples/java/{ => com/azure/security/keyvault}/secrets/HelloWorld.java (97%) rename keyvault/client/secrets/src/samples/java/{ => com/azure/security/keyvault}/secrets/HelloWorldAsync.java (76%) rename keyvault/client/secrets/src/samples/java/{ => com/azure/security/keyvault}/secrets/ListOperations.java (97%) rename keyvault/client/secrets/src/samples/java/{ => com/azure/security/keyvault}/secrets/ListOperationsAsync.java (88%) rename keyvault/client/secrets/src/samples/java/{ => com/azure/security/keyvault}/secrets/ManagingDeletedSecrets.java (96%) rename keyvault/client/secrets/src/samples/java/{ => com/azure/security/keyvault}/secrets/ManagingDeletedSecretsAsync.java (86%) diff --git a/keyvault/client/keys/src/samples/java/keys/BackupAndRestoreOperations.java b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperations.java similarity index 98% rename from keyvault/client/keys/src/samples/java/keys/BackupAndRestoreOperations.java rename to keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperations.java index dfe79bc38a12d..4dcca1ee00f2b 100644 --- a/keyvault/client/keys/src/samples/java/keys/BackupAndRestoreOperations.java +++ b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperations.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package keys; +package com.azure.security.keyvault.keys; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.keys.KeyClient; import com.azure.security.keyvault.keys.models.Key; import com.azure.security.keyvault.keys.models.RsaKeyCreateOptions; diff --git a/keyvault/client/keys/src/samples/java/keys/BackupAndRestoreOperationsAsync.java b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperationsAsync.java similarity index 94% rename from keyvault/client/keys/src/samples/java/keys/BackupAndRestoreOperationsAsync.java rename to keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperationsAsync.java index 85aa8b40157a6..ad9d479074c9a 100644 --- a/keyvault/client/keys/src/samples/java/keys/BackupAndRestoreOperationsAsync.java +++ b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/BackupAndRestoreOperationsAsync.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package keys; +package com.azure.security.keyvault.keys; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.keys.KeyAsyncClient; import com.azure.security.keyvault.keys.models.RsaKeyCreateOptions; import java.io.File; @@ -65,7 +64,7 @@ public static void main(String[] args) throws IOException, InterruptedException, // If the vault is soft-delete enabled, then you need to purge the key as well for permanent deletion. keyAsyncClient.purgeDeletedKey("CloudRsaKey").subscribe(purgeResponse -> - System.out.printf("Purge Status response %d \n", purgeResponse.statusCode())); + System.out.printf("Purge Status response %d \n", purgeResponse.statusCode())); //To ensure file is purged on server side. Thread.sleep(15000); @@ -73,7 +72,7 @@ public static void main(String[] args) throws IOException, InterruptedException, // After sometime, the key is required again. We can use the backup value to restore it in the key vault. byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); keyAsyncClient.restoreKey(backupFromFile).subscribe(keyResponse -> - System.out.printf("Restored Key with name %s \n", keyResponse.value().name())); + System.out.printf("Restored Key with name %s \n", keyResponse.value().name())); //To ensure key is restored on server side. Thread.sleep(15000); diff --git a/keyvault/client/keys/src/samples/java/keys/HelloWorld.java b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorld.java similarity index 98% rename from keyvault/client/keys/src/samples/java/keys/HelloWorld.java rename to keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorld.java index 139d4dbe1a09d..d253b2e05efc2 100644 --- a/keyvault/client/keys/src/samples/java/keys/HelloWorld.java +++ b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorld.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package keys; +package com.azure.security.keyvault.keys; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.keys.KeyClient; import com.azure.security.keyvault.keys.models.Key; import com.azure.security.keyvault.keys.models.RsaKeyCreateOptions; diff --git a/keyvault/client/keys/src/samples/java/keys/HelloWorldAsync.java b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorldAsync.java similarity index 88% rename from keyvault/client/keys/src/samples/java/keys/HelloWorldAsync.java rename to keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorldAsync.java index 411164238116c..f2bc659cac91c 100644 --- a/keyvault/client/keys/src/samples/java/keys/HelloWorldAsync.java +++ b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/HelloWorldAsync.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package keys; +package com.azure.security.keyvault.keys; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.keys.KeyAsyncClient; import com.azure.security.keyvault.keys.models.Key; import com.azure.security.keyvault.keys.models.RsaKeyCreateOptions; @@ -51,11 +50,11 @@ public static void main(String[] args) throws InterruptedException { // After one year, the Cloud Rsa Key is still required, we need to update the expiry time of the key. // The update method can be used to update the expiry attribute of the key. keyAsyncClient.getKey("CloudRsaKey").subscribe(keyResponse -> { - Key key = keyResponse.value(); - //Update the expiry time of the key. - key.expires(key.expires().plusYears(1)); - keyAsyncClient.updateKey(key).subscribe(updatedKeyResponse -> - System.out.printf("Key's updated expiry time %s \n", updatedKeyResponse.value().expires().toString())); + Key key = keyResponse.value(); + //Update the expiry time of the key. + key.expires(key.expires().plusYears(1)); + keyAsyncClient.updateKey(key).subscribe(updatedKeyResponse -> + System.out.printf("Key's updated expiry time %s \n", updatedKeyResponse.value().expires().toString())); }); Thread.sleep(2000); @@ -72,7 +71,7 @@ public static void main(String[] args) throws InterruptedException { // The Cloud Rsa Key is no longer needed, need to delete it from the key vault. keyAsyncClient.deleteKey("CloudRsaKey").subscribe(deletedKeyResponse -> - System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.value().recoveryId())); + System.out.printf("Deleted Key's Recovery Id %s \n", deletedKeyResponse.value().recoveryId())); //To ensure key is deleted on server side. Thread.sleep(30000); diff --git a/keyvault/client/keys/src/samples/java/keys/ListOperations.java b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ListOperations.java similarity index 98% rename from keyvault/client/keys/src/samples/java/keys/ListOperations.java rename to keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ListOperations.java index 3cc9401f22fc0..c13fc84ff79a0 100644 --- a/keyvault/client/keys/src/samples/java/keys/ListOperations.java +++ b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ListOperations.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package keys; +package com.azure.security.keyvault.keys; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.keys.KeyClient; import com.azure.security.keyvault.keys.models.EcKeyCreateOptions; import com.azure.security.keyvault.keys.models.Key; import com.azure.security.keyvault.keys.models.KeyBase; diff --git a/keyvault/client/keys/src/samples/java/keys/ListOperationsAsync.java b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ListOperationsAsync.java similarity index 89% rename from keyvault/client/keys/src/samples/java/keys/ListOperationsAsync.java rename to keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ListOperationsAsync.java index a86a5c9bdfb34..d707b8ce96316 100644 --- a/keyvault/client/keys/src/samples/java/keys/ListOperationsAsync.java +++ b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ListOperationsAsync.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package keys; +package com.azure.security.keyvault.keys; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.keys.KeyAsyncClient; import com.azure.security.keyvault.keys.models.EcKeyCreateOptions; import com.azure.security.keyvault.keys.models.RsaKeyCreateOptions; @@ -50,17 +49,17 @@ public static void main(String[] args) throws InterruptedException { // You need to check te type of keys already exist in your key vault. Let's list the keys and print their types. // List operations don't return the keys with key material information. So, for each returned key we call getKey to get the key with its key material information. keyAsyncClient.listKeys() - .subscribe(keyBase -> - keyAsyncClient.getKey(keyBase).subscribe(keyResponse -> - System.out.printf("Received key with name %s and type %s \n", keyResponse.value().name(), keyResponse.value().keyMaterial().kty()))); + .subscribe(keyBase -> + keyAsyncClient.getKey(keyBase).subscribe(keyResponse -> + System.out.printf("Received key with name %s and type %s \n", keyResponse.value().name(), keyResponse.value().keyMaterial().kty()))); Thread.sleep(15000); // We need the Cloud Rsa key with bigger key size, so you want to update the key in key vault to ensure it has the required size. // Calling createRsaKey on an existing key creates a new version of the key in the key vault with the new specified size. keyAsyncClient.createRsaKey(new RsaKeyCreateOptions("CloudRsaKey") - .keySize(4096) - .expires(OffsetDateTime.now().plusYears(1))).subscribe(keyResponse -> + .keySize(4096) + .expires(OffsetDateTime.now().plusYears(1))).subscribe(keyResponse -> System.out.printf("Key is created with name %s and type %s \n", keyResponse.value().name(), keyResponse.value().keyMaterial().kty())); Thread.sleep(2000); diff --git a/keyvault/client/keys/src/samples/java/keys/ManagingDeletedKeys.java b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeys.java similarity index 96% rename from keyvault/client/keys/src/samples/java/keys/ManagingDeletedKeys.java rename to keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeys.java index c64b8e47cd86d..b13bbef9e2a90 100644 --- a/keyvault/client/keys/src/samples/java/keys/ManagingDeletedKeys.java +++ b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeys.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package keys; +package com.azure.security.keyvault.keys; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.keys.KeyClient; import com.azure.security.keyvault.keys.models.DeletedKey; import com.azure.security.keyvault.keys.models.EcKeyCreateOptions; import com.azure.security.keyvault.keys.models.RsaKeyCreateOptions; @@ -53,7 +52,7 @@ public static void main(String[] args) throws IllegalArgumentException, Interrup // We accidentally Cloud Ec key. Let's recover it. // A deleted key can only be recovered if the key vault is soft-delete enabled. - keyClient.recoverDeletedKey("CloudEcKey"); + keyClient.recoverDeletedKey("CloudEcKey"); //To ensure key is recovered on server side. Thread.sleep(30000); diff --git a/keyvault/client/keys/src/samples/java/keys/ManagingDeletedKeysAsync.java b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeysAsync.java similarity index 87% rename from keyvault/client/keys/src/samples/java/keys/ManagingDeletedKeysAsync.java rename to keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeysAsync.java index 385175a599ff8..1d0e11924629e 100644 --- a/keyvault/client/keys/src/samples/java/keys/ManagingDeletedKeysAsync.java +++ b/keyvault/client/keys/src/samples/java/com/azure/security/keyvault/keys/ManagingDeletedKeysAsync.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package keys; +package com.azure.security.keyvault.keys; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.keys.KeyAsyncClient; import com.azure.security.keyvault.keys.models.EcKeyCreateOptions; import com.azure.security.keyvault.keys.models.RsaKeyCreateOptions; @@ -60,8 +59,8 @@ public static void main(String[] args) throws InterruptedException { // We accidentally deleted Cloud Ec key. Let's recover it. // A deleted key can only be recovered if the key vault is soft-delete enabled. - keyAsyncClient.recoverDeletedKey("CloudEcKey").subscribe(recoveredKeyResponse -> - System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.value().name())); + keyAsyncClient.recoverDeletedKey("CloudEcKey").subscribe(recoveredKeyResponse -> + System.out.printf("Recovered Key with name %s \n", recoveredKeyResponse.value().name())); //To ensure key is recovered on server side. Thread.sleep(10000); @@ -83,11 +82,11 @@ public static void main(String[] args) throws InterruptedException { Thread.sleep(15000); // If the keyvault is soft-delete enabled, then for permanent deletion deleted keys need to be purged. - keyAsyncClient.purgeDeletedKey("CloudRsaKey").subscribe(purgeResponse -> - System.out.printf("Storage account key purge status response %d \n", purgeResponse.statusCode())); + keyAsyncClient.purgeDeletedKey("CloudRsaKey").subscribe(purgeResponse -> + System.out.printf("Storage account key purge status response %d \n", purgeResponse.statusCode())); - keyAsyncClient.purgeDeletedKey("CloudEcKey").subscribe(purgeResponse -> - System.out.printf("Bank account key purge status response %d \n", purgeResponse.statusCode())); + keyAsyncClient.purgeDeletedKey("CloudEcKey").subscribe(purgeResponse -> + System.out.printf("Bank account key purge status response %d \n", purgeResponse.statusCode())); // To ensure key is purged on server side. Thread.sleep(15000); diff --git a/keyvault/client/secrets/src/samples/java/secrets/BackupAndRestoreOperations.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperations.java similarity index 97% rename from keyvault/client/secrets/src/samples/java/secrets/BackupAndRestoreOperations.java rename to keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperations.java index 5bceb419cf488..621c4591205c9 100644 --- a/keyvault/client/secrets/src/samples/java/secrets/BackupAndRestoreOperations.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperations.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package secrets; +package com.azure.security.keyvault.secrets; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.secrets.SecretClient; import com.azure.security.keyvault.secrets.models.Secret; import java.io.File; import java.io.FileOutputStream; diff --git a/keyvault/client/secrets/src/samples/java/secrets/BackupAndRestoreOperationsAsync.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperationsAsync.java similarity index 88% rename from keyvault/client/secrets/src/samples/java/secrets/BackupAndRestoreOperationsAsync.java rename to keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperationsAsync.java index c7f448f5a5d31..3eeed2ca6f5fe 100644 --- a/keyvault/client/secrets/src/samples/java/secrets/BackupAndRestoreOperationsAsync.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/BackupAndRestoreOperationsAsync.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package secrets; +package com.azure.security.keyvault.secrets; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.secrets.SecretAsyncClient; import com.azure.security.keyvault.secrets.models.Secret; import java.io.File; import java.io.FileOutputStream; @@ -38,9 +37,9 @@ public static void main(String[] args) throws IOException, InterruptedException, // Let's create secrets holding storage account credentials valid for 1 year. if the secret // already exists in the key vault, then a new version of the secret is created. secretAsyncClient.setSecret(new Secret("StorageAccountPassword", "f4G34fMh8v-fdsgjsk2323=-asdsdfsdf") - .expires(OffsetDateTime.now().plusYears(1))) - .subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value())); + .expires(OffsetDateTime.now().plusYears(1))) + .subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value())); Thread.sleep(2000); @@ -63,7 +62,7 @@ public static void main(String[] args) throws IOException, InterruptedException, // If the vault is soft-delete enabled, then you need to purge the secret as well for permanent deletion. secretAsyncClient.purgeDeletedSecret("StorageAccountPassword").subscribe(purgeResponse -> - System.out.printf("Purge Status response %d \n", purgeResponse.statusCode())); + System.out.printf("Purge Status response %d \n", purgeResponse.statusCode())); //To ensure file is purged on server side. Thread.sleep(15000); @@ -71,7 +70,7 @@ public static void main(String[] args) throws IOException, InterruptedException, // After sometime, the secret is required again. We can use the backup value to restore it in the key vault. byte[] backupFromFile = Files.readAllBytes(new File(backupFilePath).toPath()); secretAsyncClient.restoreSecret(backupFromFile).subscribe(secretResponse -> - System.out.printf("Restored Secret with name %s \n", secretResponse.value().name())); + System.out.printf("Restored Secret with name %s \n", secretResponse.value().name())); //To ensure secret is restored on server side. Thread.sleep(15000); diff --git a/keyvault/client/secrets/src/samples/java/secrets/HelloWorld.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorld.java similarity index 97% rename from keyvault/client/secrets/src/samples/java/secrets/HelloWorld.java rename to keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorld.java index 380d13577c150..dba0f17e0f4d7 100644 --- a/keyvault/client/secrets/src/samples/java/secrets/HelloWorld.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorld.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package secrets; +package com.azure.security.keyvault.secrets; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.secrets.SecretClient; import com.azure.security.keyvault.secrets.models.Secret; import com.azure.security.keyvault.secrets.models.SecretBase; import java.time.OffsetDateTime; diff --git a/keyvault/client/secrets/src/samples/java/secrets/HelloWorldAsync.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorldAsync.java similarity index 76% rename from keyvault/client/secrets/src/samples/java/secrets/HelloWorldAsync.java rename to keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorldAsync.java index 90c8374317408..07b9ded3ac417 100644 --- a/keyvault/client/secrets/src/samples/java/secrets/HelloWorldAsync.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/HelloWorldAsync.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package secrets; +package com.azure.security.keyvault.secrets; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.secrets.SecretAsyncClient; import com.azure.security.keyvault.secrets.models.Secret; import java.time.OffsetDateTime; @@ -32,8 +31,8 @@ public static void main(String[] args) throws InterruptedException { // Let's create a secret holding bank account credentials valid for 1 year. if the secret // already exists in the key vault, then a new version of the secret is created. secretAsyncClient.setSecret(new Secret("BankAccountPassword", "f4G34fMh8v") - .expires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value())); + .expires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse -> + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value())); Thread.sleep(2000); @@ -47,11 +46,11 @@ public static void main(String[] args) throws InterruptedException { // The update method can be used to update the expiry attribute of the secret. It cannot be used to update // the value of the secret. secretAsyncClient.getSecret("BankAccountPassword").subscribe(secretResponse -> { - Secret secret = secretResponse.value(); - //Update the expiry time of the secret. - secret.expires(secret.expires().plusYears(1)); - secretAsyncClient.updateSecret(secret).subscribe(updatedSecretResponse -> - System.out.printf("Secret's updated expiry time %s \n", updatedSecretResponse.value().expires().toString())); + Secret secret = secretResponse.value(); + //Update the expiry time of the secret. + secret.expires(secret.expires().plusYears(1)); + secretAsyncClient.updateSecret(secret).subscribe(updatedSecretResponse -> + System.out.printf("Secret's updated expiry time %s \n", updatedSecretResponse.value().expires().toString())); }); Thread.sleep(2000); @@ -60,20 +59,20 @@ public static void main(String[] args) throws InterruptedException { // To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot // change the value of the secret. secretAsyncClient.setSecret("BankAccountPassword", "bhjd4DDgsa").subscribe(secretResponse -> - System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value())); + System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value())); Thread.sleep(2000); // The bank account was closed, need to delete its credentials from the key vault. secretAsyncClient.deleteSecret("BankAccountPassword").subscribe(deletedSecretResponse -> - System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.value().recoveryId())); + System.out.printf("Deleted Secret's Recovery Id %s \n", deletedSecretResponse.value().recoveryId())); //To ensure secret is deleted on server side. Thread.sleep(30000); // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. secretAsyncClient.purgeDeletedSecret("BankAccountPassword").subscribe(purgeResponse -> - System.out.printf("Bank account secret purge status response %d \n", purgeResponse.statusCode())); + System.out.printf("Bank account secret purge status response %d \n", purgeResponse.statusCode())); //To ensure secret is purged on server side. Thread.sleep(15000); diff --git a/keyvault/client/secrets/src/samples/java/secrets/ListOperations.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperations.java similarity index 97% rename from keyvault/client/secrets/src/samples/java/secrets/ListOperations.java rename to keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperations.java index 87508fbc69229..8d7b7d98801b6 100644 --- a/keyvault/client/secrets/src/samples/java/secrets/ListOperations.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperations.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package secrets; +package com.azure.security.keyvault.secrets; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.secrets.SecretClient; import com.azure.security.keyvault.secrets.models.Secret; import com.azure.security.keyvault.secrets.models.SecretBase; diff --git a/keyvault/client/secrets/src/samples/java/secrets/ListOperationsAsync.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperationsAsync.java similarity index 88% rename from keyvault/client/secrets/src/samples/java/secrets/ListOperationsAsync.java rename to keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperationsAsync.java index a362486474664..cd1de526a862b 100644 --- a/keyvault/client/secrets/src/samples/java/secrets/ListOperationsAsync.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ListOperationsAsync.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package secrets; +package com.azure.security.keyvault.secrets; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.secrets.SecretAsyncClient; import com.azure.security.keyvault.secrets.models.Secret; import java.time.OffsetDateTime; @@ -17,6 +16,7 @@ public class ListOperationsAsync { * * @param args Unused. Arguments to the program. * @throws IllegalArgumentException when invalid key vault endpoint is passed. + * @throws InterruptedException when the thread is interrupted in sleep mode. */ public static void main(String[] args) throws InterruptedException { @@ -47,16 +47,16 @@ public static void main(String[] args) throws InterruptedException { // You need to check if any of the secrets are sharing same values. Let's list the secrets and print their values. // List operations don't return the secrets with value information. So, for each returned secret we call getSecret to get the secret with its value information. secretAsyncClient.listSecrets() - .subscribe(secretBase -> - secretAsyncClient.getSecret(secretBase).subscribe(secretResponse -> - System.out.printf("Received secret with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value()))); + .subscribe(secretBase -> + secretAsyncClient.getSecret(secretBase).subscribe(secretResponse -> + System.out.printf("Received secret with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value()))); Thread.sleep(15000); // The bank account password got updated, so you want to update the secret in key vault to ensure it reflects the new password. // Calling setSecret on an existing secret creates a new version of the secret in the key vault with the new value. secretAsyncClient.setSecret(new Secret("BankAccountPassword", "sskdjfsdasdjsd") - .expires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse -> + .expires(OffsetDateTime.now().plusYears(1))).subscribe(secretResponse -> System.out.printf("Secret is created with name %s and value %s \n", secretResponse.value().name(), secretResponse.value().value())); Thread.sleep(2000); diff --git a/keyvault/client/secrets/src/samples/java/secrets/ManagingDeletedSecrets.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java similarity index 96% rename from keyvault/client/secrets/src/samples/java/secrets/ManagingDeletedSecrets.java rename to keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java index ad0b6e78232d8..21d8cf2d2366e 100644 --- a/keyvault/client/secrets/src/samples/java/secrets/ManagingDeletedSecrets.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecrets.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package secrets; +package com.azure.security.keyvault.secrets; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.secrets.SecretClient; import com.azure.security.keyvault.secrets.models.DeletedSecret; import com.azure.security.keyvault.secrets.models.Secret; import java.time.OffsetDateTime; @@ -50,7 +49,7 @@ public static void main(String[] args) throws IllegalArgumentException, Interrup // We accidentally deleted bank account secret. Let's recover it. // A deleted secret can only be recovered if the key vault is soft-delete enabled. - client.recoverDeletedSecret("BankAccountPassword"); + client.recoverDeletedSecret("BankAccountPassword"); //To ensure secret is recovered on server side. Thread.sleep(30000); diff --git a/keyvault/client/secrets/src/samples/java/secrets/ManagingDeletedSecretsAsync.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java similarity index 86% rename from keyvault/client/secrets/src/samples/java/secrets/ManagingDeletedSecretsAsync.java rename to keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java index d1c06ec768de5..322dd4b3cd511 100644 --- a/keyvault/client/secrets/src/samples/java/secrets/ManagingDeletedSecretsAsync.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/ManagingDeletedSecretsAsync.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package secrets; +package com.azure.security.keyvault.secrets; import com.azure.identity.credential.DefaultAzureCredential; -import com.azure.security.keyvault.secrets.SecretAsyncClient; import com.azure.security.keyvault.secrets.models.Secret; import java.time.OffsetDateTime; @@ -56,8 +55,8 @@ public static void main(String[] args) throws InterruptedException { // We accidentally deleted bank account secret. Let's recover it. // A deleted secret can only be recovered if the key vault is soft-delete enabled. - secretAsyncClient.recoverDeletedSecret("BankAccountPassword").subscribe(recoveredSecretResponse -> - System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.value().name())); + secretAsyncClient.recoverDeletedSecret("BankAccountPassword").subscribe(recoveredSecretResponse -> + System.out.printf("Recovered Secret with name %s \n", recoveredSecretResponse.value().name())); //To ensure secret is recovered on server side. Thread.sleep(10000); @@ -80,11 +79,11 @@ public static void main(String[] args) throws InterruptedException { Thread.sleep(15000); // If the key vault is soft-delete enabled, then for permanent deletion deleted secrets need to be purged. - secretAsyncClient.purgeDeletedSecret("StorageAccountPassword").subscribe(purgeResponse -> - System.out.printf("Storage account secret purge status response %d \n", purgeResponse.statusCode())); + secretAsyncClient.purgeDeletedSecret("StorageAccountPassword").subscribe(purgeResponse -> + System.out.printf("Storage account secret purge status response %d \n", purgeResponse.statusCode())); - secretAsyncClient.purgeDeletedSecret("BankAccountPassword").subscribe(purgeResponse -> - System.out.printf("Bank account secret purge status response %d \n", purgeResponse.statusCode())); + secretAsyncClient.purgeDeletedSecret("BankAccountPassword").subscribe(purgeResponse -> + System.out.printf("Bank account secret purge status response %d \n", purgeResponse.statusCode())); // To ensure secret is purged on server side. Thread.sleep(15000); diff --git a/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java index 71fba64e2252e..297a0a3dc7f0e 100644 --- a/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java +++ b/keyvault/client/secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java @@ -17,7 +17,7 @@ public final class SecretClientJavaDocCodeSnippets { public void getSecret() { SecretClient secretClient = getSecretClient(); // BEGIN: com.azure.keyvault.secretclient.getSecret#secretBase - for(SecretBase secret : secretClient.listSecrets()){ + for (SecretBase secret : secretClient.listSecrets()) { Secret secretWithValue = secretClient.getSecret(secret).value(); System.out.printf("Secret is returned with name %s and value %s %n", secretWithValue.name(), secretWithValue.value()); From 97cde16adf94d527e6769fce34a8d545c03682be Mon Sep 17 00:00:00 2001 From: Jonathan Giles Date: Fri, 5 Jul 2019 16:09:02 +1200 Subject: [PATCH 098/147] Add Identity to list of preview libraries (#4288) --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a148334fe29d8..02243f5344921 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ These preview libraries can be easily identified by their folder, package, and n 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) - [Storage Blobs](storage/client/README.md) @@ -53,4 +54,4 @@ Libraries which enable you to provision specific resources. They are responsible ## Contributing For details on contributing to this repository, see the [contributing guide](CONTRIBUTING.md). -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2FREADME.png) \ No newline at end of file +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2FREADME.png) From 90ff34497a5167249b1fc62ad4e30a5da2b281aa Mon Sep 17 00:00:00 2001 From: Jonathan Giles Date: Fri, 5 Jul 2019 16:09:24 +1200 Subject: [PATCH 099/147] Update README.md (#4287) --- appconfiguration/client/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appconfiguration/client/README.md b/appconfiguration/client/README.md index cdc77d4139f32..c283c5715b6d7 100644 --- a/appconfiguration/client/README.md +++ b/appconfiguration/client/README.md @@ -20,8 +20,8 @@ Use the client library for App Configuration to create and manage application co ```xml com.azure - azure-app-configuration - 1.0.0-SNAPSHOT + azure-data-appconfiguration + 1.0.0-preview.1 ``` From 51f8f438d0a690e3d8ec748ccacd0a4b06f74fe6 Mon Sep 17 00:00:00 2001 From: Jonathan Giles Date: Fri, 5 Jul 2019 16:09:55 +1200 Subject: [PATCH 100/147] First pass at improved readme.md files for /core and /core/azure-core (#4283) * First pass at improved readme.md files for /core and /core/azure-core --- core/README.md | 133 ++++++-------------------------------- core/azure-core/README.md | 77 ++++++++++++++++++++++ 2 files changed, 95 insertions(+), 115 deletions(-) create mode 100644 core/azure-core/README.md diff --git a/core/README.md b/core/README.md index ce52d05ef7290..ec88ce9e1a077 100644 --- a/core/README.md +++ b/core/README.md @@ -1,124 +1,27 @@ -[![Build Status](https://travis-ci.org/Azure/autorest-clientruntime-for-java.svg?branch=v2)](https://travis-ci.org/Azure/autorest-clientruntime-for-java) +# Azure Core shared library for Java -# AutoRest Client Runtimes for Java -The runtime libraries for [AutoRest](https://github.com/azure/autorest) generated Java clients. +[![Build Documentation](https://img.shields.io/badge/documentation-published-blue.svg)](https://azure.github.io/azure-sdk-for-java/track2reports/index.html) -## Usage +Azure Core provides shared primitives, abstractions, and helpers for modern Java Azure SDK client libraries. These libraries follow the [Azure SDK Design Guidelines for JavaT](https://azuresdkspecs.z5.web.core.windows.net/JavaSpec.html) and can be easily identified by package names starting with `com.azure` and module names starting with `azure-`, e.g. `com.azure.storage.blobs` would be found within the `/sdk/storage/azure-storage-blob` directory. A more complete list of client libraries using Azure Core can be found [here](https://github.com/Azure/azure-sdk-for-java). -### Prerequisites +Azure Core allows client libraries to expose common functionality in a consistent fashion, so that once you learn how to use these APIs in one client library, you will know how to use them in other client libraries. -- JDK 1.8 +The main shared concepts of Azure Core (and therefore all Azure client libraries using Azure Core) include: -### Download +- Configuring service clients, e.g. configuring retries, logging, etc. +- Accessing HTTP response details (`Response`). +- Calling long running operations (`Poller`). +- Paging and asynchronous streams (`PagedFlux`). +- Exceptions for reporting errors from service requests in a consistent fashion. +- Abstractions for representing Azure SDK credentials. -```xml - - - - com.microsoft.rest.v3 - client-runtime - 2.0.0-beta4 - - - - - com.microsoft.azure.v3 - azure-client-runtime - 2.0.0-beta4 - - - - com.microsoft.azure.v3 - azure-client-authentication - 2.0.0-beta4 - - - +## Sub-projects - - - io.netty - netty-tcnative-boringssl-static - 2.0.8.Final - ${os.detected.classifier} - +Azure Core is split into a number of sub-components: - - - io.netty - netty-transport-native-epoll - 4.1.23.Final - ${os.detected.classifier} - +* [azure-core](azure-core) is the primary library, used by all client libraries to offer the functionality outlined above. +* [azure-core-amqp](azure-core-amqp) provides functionality related to AMQP (Advanced Message Queuing Protocol). +* [azure-core-management](azure-core-management) provides APIs used by the Azure management libraries, but which are redundant to client libraries. +* [azure-core-test](azure-core-test) provides utilities and API to make writing tests for Azure Core simpler and consistent. - - - io.netty - netty-transport-native-kqueue - 4.1.23.Final - ${os.detected.classifier} - - - - - - - - kr.motd.maven - os-maven-plugin - 1.6.0 - - - -``` - -### Usage - -Non-Azure generated clients will have a constructor that takes no arguments for simple scenarios, while Azure generated clients will require a `ServiceClientCredentials` argument at a minimum. - -If you want to have more control over configuration, consider using HttpPipeline. This enables performing transformations on all HTTP messages sent by a client, similar to interceptors or filters in other HTTP clients. - -You can build an HttpPipeline out of a sequence of RequestPolicyFactories. These policies will get applied in-order to outgoing requests, and then in reverse order for incoming responses. HttpPipelineBuilder includes convenience methods for adding several built-in RequestPolicyFactories, including policies for credentials, logging, response decoding (deserialization), cookies support, and several others. - -```java -// For Java generator -HttpPipeline pipeline = new HttpPipelineBuilder() - .withHostPolicy("http://localhost") - .withDecodingPolicy() - .build(); -AutoRestJavaClient client = new AutoRestJavaClientImpl(pipeline); - -// For Azure.Java generator -HttpPipeline azurePipeline = new HttpPipelineBuilder() - .withCredentialsPolicy(AzureCliCredentials.create()) - .withHttpLoggingPolicy(HttpLogDetailLevel.HEADERS) - .withDecodingPolicy() - .build(); -FooServiceClient azureClient = new FooServiceClientImpl(azurePipeline); -``` - -## Components - -### client-runtime -This is the generic runtime. Add this package as a dependency if you are using `Java` generator in AutoRest. This package depends on [Netty](https://github.com/netty/netty), [Jackson](http://wiki.fasterxml.com/JacksonHome), and [RxJava](https://github.com/ReactiveX/RxJava) for making and processing REST requests. - -### azure-client-runtime -This is the runtime with Azure Resource Management customizations. Add this package as a dependency if you are using `--azure-arm` or `--azure-arm --fluent` generator flags in AutoRest. - -This combination provides a set of Azure specific behaviors, including long running operations, special handling of HEAD operations, and paginated `list()` calls. - -### azure-client-authentication (beta) -This package provides access to Active Directory authentication on JDK using OrgId or application ID / secret combinations. There are currently 3 types of authentication provided: - -- Service principal authentication: `ApplicationTokenCredentials` -- Username / password login without multi-factor auth: `UserTokenCredentials` -- Use the credentials logged in [Azure CLI](https://github.com/azure/azure-cli): `AzureCliCredentials` - -### azure-android-client-authentication (beta) -This package provides access to Active Directory authentication on Android. You can login with Microsoft accounts, OrgId, with or without multi-factor auth. - -## Build -To build this repository, you will need maven 2.0+ and gradle 1.6+. - -## Contributing -This repository is for runtime & authentication specifically. For issues in the generated code, please report in [AutoRest](https://github.com/Azure/autorest). For bugs in the Azure SDK, please report in [Azure SDK for Java](https://github.com/Azure/azure-sdk-for-java). If you are unsure, please file here and state that clearly in the issue. Pull requests are welcomed with clear Javadocs. +For documentation on using Azure Core, refer to the [azure-core readme](azure-core). diff --git a/core/azure-core/README.md b/core/azure-core/README.md new file mode 100644 index 0000000000000..5323106dd8d0f --- /dev/null +++ b/core/azure-core/README.md @@ -0,0 +1,77 @@ +# Azure Core client library for Java + +[![Build Documentation](https://img.shields.io/badge/documentation-published-blue.svg)](https://azure.github.io/azure-sdk-for-java/track2reports/index.html) + +Azure Core provides shared primitives, abstractions, and helpers for modern Java Azure SDK client libraries. These libraries follow the [Azure SDK Design Guidelines for JavaT](https://azuresdkspecs.z5.web.core.windows.net/JavaSpec.html) and can be easily identified by package names starting with `com.azure` and module names starting with `azure-`, e.g. `com.azure.storage.blobs` would be found within the `/sdk/storage/azure-storage-blob` directory. A more complete list of client libraries using Azure Core can be found [here](https://github.com/Azure/azure-sdk-for-java). + +Azure Core allows client libraries to expose common functionality in a consistent fashion, so that once you learn how to use these APIs in one client library, you will know how to use them in other client libraries. + +## Getting started + +Typically, you will not need to install or specifically depend on Azure Core, instead it will be transitively downloaded by your build tool when you depend on of the client libraries using it. In case you want to depend on it explicitly (to implement your own client library, for example), include the following Maven dependency: + +```xml + + com.azure + azure-core + 1.0.0-preview.2 + +``` + +For details on including this dependency in other build tools (Gradle, SBT, etc), refer [here](https://search.maven.org/artifact/com.azure/azure-core). + +## Key concepts + +The key concepts of Azure Core (and therefore all Azure client libraries using Azure Core) include: + +- Configuring service clients, e.g. configuring retries, logging, etc. +- Accessing HTTP response details (`Response`). +- Calling long running operations (`Poller`). +- Paging and asynchronous streams (`PagedFlux`). +- Exceptions for reporting errors from service requests in a consistent fashion. +- Abstractions for representing Azure SDK credentials. + +These will be introduced by way of the examples presented below. + +## Examples + +### Accessing HTTP Response Details Using `Response` + +_Service clients_ have methods that can be used to call Azure services. We refer to these client methods _service methods_. +_Service methods_ return a shared Azure Core type `Response`. This type provides access to both the deserialized result of the service call, and to the details of the HTTP response returned from the server. + +### HTTP pipelines with `HttpPipeline` + +Coming soon ... + +### Exception Hierarchy with `AzureException` + +Coming soon ... + +### Pagination with `PagedFlux` + +Coming soon ... + +### Long Running Operations with `Poller` + +Coming soon ... + +## Next steps + +Get started with some of the Azure libraries that are [built using Azure Core](https://github.com/Azure/azure-sdk-for-java). + +## Troubleshooting + +If you encounter any bugs, please file issues via [GitHub Issues](https://github.com/Azure/azure-sdk-for-java/issues) or checkout +[StackOverflow for Azure Java SDK](http://stackoverflow.com/questions/tagged/azure-java-sdk). + +## Contributing + +If you would like to become an active contributor to this project please follow the instructions provided in +[Microsoft Azure Projects Contribution Guidelines](http://azure.github.io/guidelines.html). + +1. Fork it +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create new Pull Request From 2a7ae735de48d37aa344cdeb35357e72381872f4 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Fri, 5 Jul 2019 10:41:27 -0700 Subject: [PATCH 101/147] Add CI config for mediaservices. (#4292) --- sdk/mediaservices/ci.yml | 23 +++++++++++++++++++++++ sdk/mediaservices/pom.service.xml | 14 ++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 sdk/mediaservices/ci.yml create mode 100644 sdk/mediaservices/pom.service.xml diff --git a/sdk/mediaservices/ci.yml b/sdk/mediaservices/ci.yml new file mode 100644 index 0000000000000..92324f8824980 --- /dev/null +++ b/sdk/mediaservices/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/mediaservices/ + +pr: + branches: + include: + - master + paths: + include: + - sdk/mediaservices/ + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: mediaservices \ No newline at end of file diff --git a/sdk/mediaservices/pom.service.xml b/sdk/mediaservices/pom.service.xml new file mode 100644 index 0000000000000..b7cdd074ae8d5 --- /dev/null +++ b/sdk/mediaservices/pom.service.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.azure + azure-mediaservices-service + pom + 1.0.0 + + + + From 50d8ce6a450e436e1705a7f5eb40d1864e40dcf7 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Fri, 5 Jul 2019 12:12:38 -0700 Subject: [PATCH 102/147] Add template CI configuration. (#4294) --- sdk/template/ci.yml | 23 +++++++++++++++++++++++ sdk/template/pom.service.xml | 14 ++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 sdk/template/ci.yml create mode 100644 sdk/template/pom.service.xml diff --git a/sdk/template/ci.yml b/sdk/template/ci.yml new file mode 100644 index 0000000000000..a02392a0674f8 --- /dev/null +++ b/sdk/template/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/template/ + +pr: + branches: + include: + - master + paths: + include: + - sdk/template/ + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: template \ No newline at end of file diff --git a/sdk/template/pom.service.xml b/sdk/template/pom.service.xml new file mode 100644 index 0000000000000..960a275f07de7 --- /dev/null +++ b/sdk/template/pom.service.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.azure + azure-template-service + pom + 1.0.0 + + microsoft-sdk-template + + From 0c03f51af084fc1b204c23da6ad77864a4614891 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Fri, 5 Jul 2019 12:37:33 -0700 Subject: [PATCH 103/147] Fix module ref. (#4295) --- sdk/template/pom.service.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/template/pom.service.xml b/sdk/template/pom.service.xml index 960a275f07de7..f8b2c05a9ef67 100644 --- a/sdk/template/pom.service.xml +++ b/sdk/template/pom.service.xml @@ -9,6 +9,6 @@ pom 1.0.0 - microsoft-sdk-template + azure-sdk-template From 1bec5d2d782c47df2f9de22f73c75b2c9289bd56 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Fri, 5 Jul 2019 13:21:44 -0700 Subject: [PATCH 104/147] Setup CosmosDB CI. (#4296) --- sdk/cosmosdb/ci.yml | 23 +++++++++++++++++++++++ sdk/cosmosdb/pom.service.xml | 19 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 sdk/cosmosdb/ci.yml create mode 100644 sdk/cosmosdb/pom.service.xml diff --git a/sdk/cosmosdb/ci.yml b/sdk/cosmosdb/ci.yml new file mode 100644 index 0000000000000..c2a1e5d1f072e --- /dev/null +++ b/sdk/cosmosdb/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/cosmosdb/ + +pr: + branches: + include: + - master + paths: + include: + - sdk/cosmosdb/ + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: cosmosdb \ No newline at end of file diff --git a/sdk/cosmosdb/pom.service.xml b/sdk/cosmosdb/pom.service.xml new file mode 100644 index 0000000000000..56f12fc9d934b --- /dev/null +++ b/sdk/cosmosdb/pom.service.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + com.azure + azure-keyvault-service + pom + 1.0.0 + + microsoft-azure-keyvault + microsoft-azure-keyvault-core + microsoft-azure-keyvault-webkey + microsoft-azure-keyvault-cryptography + microsoft-azure-keyvault-extensions + microsoft-azure-keyvault-complete + + From 3677da67b0da084066c8282b65c59e3ffefcf60a Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Fri, 5 Jul 2019 15:02:15 -0700 Subject: [PATCH 105/147] Update App Configuration README with correct links. (#4298) * Update README with correct links. * Remove broken JDK link * Reorganize links. --- appconfiguration/client/README.md | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/appconfiguration/client/README.md b/appconfiguration/client/README.md index c283c5715b6d7..3d645280fa540 100644 --- a/appconfiguration/client/README.md +++ b/appconfiguration/client/README.md @@ -11,7 +11,7 @@ Use the client library for App Configuration to create and manage application co ### Prerequisites -- [Java Development Kit (JDK)][jdk] with version 8 or above +- Java Development Kit (JDK) with version 8 or above - [Azure Subscription][azure_subscription] - [App Configuration Store][app_config_store] @@ -106,7 +106,7 @@ An application that has a large set of configurations that it needs to periodica ConfigurationAsyncClient client = new ConfigurationAsyncClient.builder() .credentials(new ConfigurationClientCredentials(appConfigConnectionString)) .build(); - + client.listSettings(new SettingSelection().label(periodicUpdateLabel)) .subscribe(setting -> updateConfiguration(setting)); ``` @@ -168,7 +168,7 @@ ConfigurationSetting setting = client.deleteSetting("some_key"); ### General -When you interact with App Configuration using this Java client library, errors returned by the service correspond to the same HTTP status codes returned for [REST API][azconfig_rest] requests. For example, if you try to retrieve a Configuration Setting that doesn't exist in your Configuration Store, a `404` error is returned, indicating `Not Found`. +When you interact with App Configuration using this Java client library, errors returned by the service correspond to the same HTTP status codes returned for [REST API][rest_api] requests. For example, if you try to retrieve a Configuration Setting that doesn't exist in your Configuration Store, a `404` error is returned, indicating `Not Found`. ## Next steps @@ -185,14 +185,12 @@ If you would like to become an active contributor to this project please follow 5. Create new Pull Request -[source_code]: https://github.com/Azure/azure-sdk-for-java/tree/master/applicationconfig/client/src -[package]:not-valid-link -[api_documentation]: not-valid-link -[azconfig_docs]: https://docs.microsoft.com/en-us/azure/azure-app-configuration/ -[jdk]: https://docs.microsoft.com/en-us/java/azure/java-supported-jdk-runtime?view=azure-java-stable -[maven]: https://maven.apache.org/ -[azure_subscription]: https://azure.microsoft.com/en-us/free/ +[api_documentation]: https://aka.ms/java-docs [app_config_store]: https://docs.microsoft.com/en-us/azure/azure-app-configuration/quickstart-dotnet-core-app#create-an-app-configuration-store +[azconfig_docs]: https://docs.microsoft.com/en-us/azure/azure-app-configuration/ [azure_cli]: https://docs.microsoft.com/cli/azure +[azure_subscription]: https://azure.microsoft.com/en-us/free/ +[maven]: https://maven.apache.org/ +[package]: https://search.maven.org/artifact/com.azure/azure-data-appconfiguration [rest_api]: https://github.com/Azure/AppConfiguration#rest-api-reference -[azconfig_rest]: https://github.com/Azure/AppConfiguration#rest-api-reference +[source_code]: src From a924a96f7d05a56ee16ca48d774ae6d152405893 Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Fri, 5 Jul 2019 15:02:33 -0700 Subject: [PATCH 106/147] Replace Application Configuration with product name. (#4299) --- appconfiguration/client/pom.xml | 4 ++-- .../azure/data/appconfiguration/ConfigurationAsyncClient.java | 2 +- .../credentials/ConfigurationClientCredentials.java | 4 ++-- .../azure/data/appconfiguration/credentials/package-info.java | 2 +- .../data/appconfiguration/implementation/package-info.java | 2 +- .../data/appconfiguration/models/ConfigurationSetting.java | 2 +- .../java/com/azure/data/appconfiguration/models/Range.java | 2 +- .../azure/data/appconfiguration/models/SettingSelector.java | 2 +- .../java/com/azure/data/appconfiguration/package-info.java | 2 +- .../policy/ConfigurationCredentialsPolicy.java | 4 ++-- .../com/azure/data/appconfiguration/policy/package-info.java | 2 +- .../client/src/samples/java/ConfigurationSets.java | 2 +- appconfiguration/client/src/samples/java/HelloWorld.java | 2 +- 13 files changed, 16 insertions(+), 16 deletions(-) diff --git a/appconfiguration/client/pom.xml b/appconfiguration/client/pom.xml index 457fed3587a86..325f4206dd439 100644 --- a/appconfiguration/client/pom.xml +++ b/appconfiguration/client/pom.xml @@ -15,8 +15,8 @@ azure-data-appconfiguration 1.0.0-SNAPSHOT - Microsoft Azure client library for Application Configuration - This package contains the Microsoft Azure Application Configuration client library. + Microsoft Azure client library for App Configuration + This package contains the Microsoft Azure App Configuration client library. https://github.com/Azure/azure-sdk-for-java diff --git a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java index f31f3588b4109..36f289ec727a2 100644 --- a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java +++ b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java @@ -60,7 +60,7 @@ public final class ConfigurationAsyncClient { * Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}. * Each service call goes through the {@code pipeline}. * - * @param serviceEndpoint URL for the Application configuration service. + * @param serviceEndpoint URL for the App Configuration service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ ConfigurationAsyncClient(URL serviceEndpoint, HttpPipeline pipeline) { diff --git a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/credentials/ConfigurationClientCredentials.java b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/credentials/ConfigurationClientCredentials.java index d2ddeb20db81b..e716e21f62fba 100644 --- a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/credentials/ConfigurationClientCredentials.java +++ b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/credentials/ConfigurationClientCredentials.java @@ -29,7 +29,7 @@ import java.util.stream.Collectors; /** - * Credentials that authorizes requests to Azure Application Configuration. It uses content within the HTTP request to + * Credentials that authorizes requests to Azure App Configuration. It uses content within the HTTP request to * generate the correct "Authorization" header value. {@link ConfigurationCredentialsPolicy} ensures that the content * exists in the HTTP request so that a valid authorization value is generated. * @@ -47,7 +47,7 @@ public class ConfigurationClientCredentials { private final AuthorizationHeaderProvider headerProvider; /** - * Creates an instance that is able to authorize requests to Azure Application Configuration service. + * Creates an instance that is able to authorize requests to Azure App Configuration service. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value};secret={secret_value}" * @throws NoSuchAlgorithmException When the HMAC-SHA256 MAC algorithm cannot be instantiated. diff --git a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/credentials/package-info.java b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/credentials/package-info.java index 2bb81ada22b23..0e1949b58f4f0 100644 --- a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/credentials/package-info.java +++ b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/credentials/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** - * Package containing classes used to authenticate with Azure Application Configuration service. + * Package containing classes used to authenticate with Azure App Configuration service. */ package com.azure.data.appconfiguration.credentials; diff --git a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/implementation/package-info.java b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/implementation/package-info.java index 986a8a5b60326..1c204d2ce1c38 100644 --- a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/implementation/package-info.java +++ b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/implementation/package-info.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** - * Package containing implementation classes for communicating with Azure Application Configuration service. + * Package containing implementation classes for communicating with Azure App Configuration service. * Should not be used. */ package com.azure.data.appconfiguration.implementation; diff --git a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/ConfigurationSetting.java b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/ConfigurationSetting.java index d97d8a0c117be..24bf8709e7e9f 100644 --- a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/ConfigurationSetting.java +++ b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/ConfigurationSetting.java @@ -168,7 +168,7 @@ public OffsetDateTime lastModified() { * Gets whether or not the configuration setting is locked. If the setting is locked, then no modifications can be * made to this setting. * - * This is a readonly property. It is populated from responses from the Azure Application Configuration + * This is a readonly property. It is populated from responses from the Azure App Configuration * service. * * @return true if locked; false otherwise. diff --git a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/Range.java b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/Range.java index fe0b67bb17645..93a166235d416 100644 --- a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/Range.java +++ b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/Range.java @@ -8,7 +8,7 @@ /** * A configuration for selecting a range of revisions when retrieving configuration setting revisions from the - * Application Configuration service. + * App Configuration service. * * @see ConfigurationAsyncClient#listSettingRevisions(SettingSelector) * @see ConfigurationClient#listSettingRevisions(SettingSelector) diff --git a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/SettingSelector.java b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/SettingSelector.java index 95de7d24bc970..90856854f1aa4 100644 --- a/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/SettingSelector.java +++ b/appconfiguration/client/src/main/java/com/azure/data/appconfiguration/models/SettingSelector.java @@ -10,7 +10,7 @@ import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; /** - * A set of options for selecting configuration settings from Application Configuration service. + * A set of options for selecting configuration settings from App Configuration service. * *