From 918038eb278009c44884254693870c90e85bef9f Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Wed, 15 Jul 2020 22:15:34 -0700 Subject: [PATCH 1/6] Updated spring-data-cosmos to cosmos V4 dependency --- sdk/cosmos/azure-spring-data-cosmos/README.md | 8 +- sdk/cosmos/azure-spring-data-cosmos/pom.xml | 35 +- .../azure/spring/data/cosmos/Constants.java | 14 +- .../spring/data/cosmos/CosmosDBFactory.java | 123 ++++ .../spring/data/cosmos/CosmosDbFactory.java | 120 ---- ...{CosmosdbUtils.java => CosmosDBUtils.java} | 0 .../data/cosmos/common/CosmosDbUtils.java | 48 ++ .../data/cosmos/common/TelemetrySender.java | 9 +- .../config/AbstractCosmosConfiguration.java | 86 +-- .../config/CosmosConfigurationSupport.java | 2 +- .../data/cosmos/config/CosmosDBConfig.java | 330 ++-------- .../data/cosmos/core/CosmosOperations.java | 56 +- .../data/cosmos/core/CosmosTemplate.java | 581 ++++++++--------- .../cosmos/core/ReactiveCosmosOperations.java | 27 +- .../cosmos/core/ReactiveCosmosTemplate.java | 583 ++++++++---------- .../data/cosmos/core/ResponseDiagnostics.java | 89 +-- .../core/ResponseDiagnosticsProcessor.java | 4 +- .../core/convert/MappingCosmosConverter.java | 89 ++- .../generator/AbstractQueryGenerator.java | 20 +- .../core/generator/CountQueryGenerator.java | 2 +- .../generator/FindQuerySpecGenerator.java | 2 +- .../core/generator/QuerySpecGenerator.java | 2 +- .../core/mapping/CosmosPersistentEntity.java | 7 - .../data/cosmos/core/mapping/Document.java | 10 +- .../core/mapping/DocumentIndexingPolicy.java | 6 +- .../cosmos/core/mapping/PartitionKey.java | 2 +- .../cosmos/core/query/CosmosPageRequest.java | 9 +- .../data/cosmos/core/query/CriteriaType.java | 2 +- .../exception/CosmosDBAccessException.java | 22 +- .../exception/CosmosDBExceptionUtils.java | 17 +- .../exception/DatabaseCreationException.java | 2 +- .../exception/IllegalCollectionException.java | 2 +- .../exception/IllegalQueryException.java | 2 +- .../cosmos/repository/CosmosRepository.java | 2 +- .../repository/ReactiveCosmosRepository.java | 2 +- ...osmosRepositoryConfigurationExtension.java | 6 +- .../config/EnableCosmosRepositories.java | 4 +- .../EnableReactiveCosmosRepositories.java | 4 +- ...osmosRepositoryConfigurationExtension.java | 6 +- .../query/CosmosEntityMetadata.java | 8 - .../repository/query/CosmosQueryCreator.java | 4 +- .../repository/query/PartTreeCosmosQuery.java | 2 +- .../query/PartTreeReactiveCosmosQuery.java | 3 +- .../query/ReactiveCosmosEntityMetadata.java | 8 - .../query/ReactiveCosmosQueryCreator.java | 2 +- .../support/CosmosEntityInformation.java | 63 +- .../support/CosmosRepositoryFactory.java | 2 +- .../ReactiveCosmosRepositoryFactory.java | 2 +- .../ReactiveCosmosRepositoryFactoryBean.java | 2 +- .../support/SimpleCosmosRepository.java | 40 +- .../SimpleReactiveCosmosRepository.java | 10 +- .../com/azure/cosmos/AppConfiguration.java | 29 +- .../cosmos/AppConfigurationCodeSnippet.java | 20 +- ...roperties.java => CosmosDBProperties.java} | 12 +- .../DocumentIndexingPolicyCodeSnippet.java | 4 +- .../java/com/azure/cosmos/MyDocument.java | 2 +- .../samples/java/com/azure/cosmos/User.java | 2 +- .../cosmos/UserRepositoryConfiguration.java | 31 +- .../java/com/azure/cosmos/UserSample.java | 2 +- .../data/cosmos/CosmosDBFactoryTestIT.java | 74 +++ .../data/cosmos/CosmosDbFactoryTestIT.java | 67 -- .../spring/data/cosmos/UserAgentTestIT.java | 38 -- .../data/cosmos/common/DynamicContainer.java | 2 +- .../common/ExpressionResolverUnitTest.java | 5 - .../data/cosmos/common/MemoizerUnitTest.java | 5 - .../common/ResponseDiagnosticsTestUtils.java | 11 +- .../data/cosmos/common/TestConstants.java | 45 +- .../config/AbstractCosmosConfigurationIT.java | 67 +- .../data/cosmos/core/CosmosTemplateIT.java | 95 ++- .../core/CosmosTemplateIllegalTest.java | 5 +- .../core/CosmosTemplatePartitionIT.java | 31 +- .../cosmos/core/CosmosTemplateUnitTest.java | 12 +- .../cosmos/core/ReactiveCosmosTemplateIT.java | 148 +++-- .../ReactiveCosmosTemplatePartitionIT.java | 22 +- .../MappingCosmosConverterUnitTest.java | 51 +- .../data/cosmos/domain/PageablePerson.java | 3 +- .../spring/data/cosmos/domain/Person.java | 3 +- .../spring/data/cosmos/domain/Project.java | 3 +- .../spring/data/cosmos/domain/Question.java | 4 +- .../azure/spring/data/cosmos/domain/Role.java | 21 +- .../data/cosmos/domain/SortedProject.java | 3 +- .../data/cosmos/domain/SpELBeanStudent.java | 2 +- .../cosmos/domain/SpELPropertyStudent.java | 2 +- .../spring/data/cosmos/domain/Student.java | 3 +- .../data/cosmos/domain/TimeToLiveSample.java | 2 +- .../cosmos/performance/PerfConfiguration.java | 8 +- .../performance/PerformanceCompare.java | 28 +- .../cosmos/performance/domain/PerfPerson.java | 5 +- .../repository/PerfPersonRepository.java | 2 +- .../performance/service/SdkService.java | 187 +++--- .../cosmos/performance/utils/Constants.java | 4 +- .../performance/utils/DatabaseUtils.java | 36 +- .../repository/CosmosAnnotationUnitTest.java | 23 +- .../SimpleCosmosRepositoryIllegalTest.java | 2 +- .../SimpleCosmosRepositoryUnitTest.java | 6 +- .../repository/TestRepositoryConfig.java | 53 +- .../integration/AddressRepositoryIT.java | 13 +- .../integration/ContactRepositoryIT.java | 11 +- .../integration/CosmosAnnotationIT.java | 28 +- .../integration/CustomerRepositoryIT.java | 8 +- .../IntegerIdDomainRepositoryIT.java | 18 +- .../integration/MemoRepositoryIT.java | 14 +- .../PageableAddressRepositoryIT.java | 29 +- .../integration/PageableMemoRepositoryIT.java | 37 +- .../PageablePersonRepositoryIT.java | 12 +- .../integration/ProjectRepositoryIT.java | 23 +- .../integration/ProjectRepositorySortIT.java | 10 +- .../integration/QuestionRepositoryIT.java | 12 +- .../ReactiveCourseRepositoryIT.java | 6 +- .../integration/SpELCosmosDBAnnotationIT.java | 18 +- .../integration/SquareRepositoryIT.java | 4 +- .../integration/StudentRepositoryIT.java | 8 +- .../repository/AddressRepository.java | 2 +- .../repository/ContactRepository.java | 2 +- .../repository/CustomerRepository.java | 2 +- .../repository/IntegerIdDomainRepository.java | 2 +- .../repository/repository/MemoRepository.java | 2 +- .../repository/PartitionPersonRepository.java | 2 +- .../repository/PersonRepository.java | 2 +- .../repository/ProjectRepository.java | 2 +- .../repository/QuestionRepository.java | 2 +- .../repository/ReactiveCourseRepository.java | 2 +- .../repository/SortedProjectRepository.java | 2 +- .../repository/SquareRepository.java | 2 +- .../repository/StudentRepository.java | 2 +- .../CosmosEntityInformationUnitTest.java | 6 +- .../CosmosRepositoryFactoryBeanUnitTest.java | 5 - .../src/test/resources/application.properties | 5 +- 128 files changed, 1812 insertions(+), 2142 deletions(-) create mode 100644 sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDBFactory.java delete mode 100644 sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDbFactory.java rename sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/{CosmosdbUtils.java => CosmosDBUtils.java} (100%) create mode 100644 sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java rename sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/{CosmosDbProperties.java => CosmosDBProperties.java} (80%) create mode 100644 sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDBFactoryTestIT.java delete mode 100644 sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDbFactoryTestIT.java delete mode 100644 sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/UserAgentTestIT.java diff --git a/sdk/cosmos/azure-spring-data-cosmos/README.md b/sdk/cosmos/azure-spring-data-cosmos/README.md index 16f9b4d26b1b..6cabc2e51a72 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/README.md +++ b/sdk/cosmos/azure-spring-data-cosmos/README.md @@ -122,7 +122,7 @@ For reactive repository support, use `@EnableReactiveCosmosRepositories` ### Response Diagnostics String and Query Metrics 2.2.x supports Response Diagnostics String and Query Metrics. -Set `populateQueryMetrics` flag to true in application.properties to enable query metrics. +Set `queryMetricsEnabled` flag to true in application.properties to enable query metrics. In addition to setting the flag, implement `ResponseDiagnosticsProcessor` to log diagnostics information. @@ -145,8 +145,8 @@ public class AppConfiguration extends AbstractCosmosConfiguration { @Value("${azure.cosmosdb.database}") private String dbName; - @Value("${azure.cosmosdb.populateQueryMetrics}") - private boolean populateQueryMetrics; + @Value("${azure.cosmosdb.queryMetricsEnabled}") + private boolean queryMetricsEnabled; private CosmosKeyCredential cosmosKeyCredential; @@ -154,7 +154,7 @@ public class AppConfiguration extends AbstractCosmosConfiguration { this.cosmosKeyCredential = new CosmosKeyCredential(key); CosmosDBConfig cosmosdbConfig = CosmosDBConfig.builder(uri, this.cosmosKeyCredential, dbName).build(); - cosmosdbConfig.setPopulateQueryMetrics(populateQueryMetrics); + cosmosdbConfig.setQueryMetricEnabled(queryMetricsEnabled); cosmosdbConfig.setResponseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()); return cosmosdbConfig; } diff --git a/sdk/cosmos/azure-spring-data-cosmos/pom.xml b/sdk/cosmos/azure-spring-data-cosmos/pom.xml index c08922070a6e..72e895f07545 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/pom.xml +++ b/sdk/cosmos/azure-spring-data-cosmos/pom.xml @@ -42,48 +42,41 @@ - org.springframework spring-web 5.2.6.RELEASE - org.springframework spring-beans 5.2.6.RELEASE - org.springframework spring-context 5.2.6.RELEASE - org.springframework spring-tx 5.2.6.RELEASE - org.springframework.data spring-data-commons 2.3.0.RELEASE - org.springframework spring-expression 5.2.6.RELEASE - com.microsoft.azure + com.azure azure-cosmos - 3.7.3 + 4.2.0-beta.1 - com.fasterxml.jackson.module jackson-module-parameter-names @@ -104,18 +97,21 @@ json 20140107 - org.javatuples javatuples 1.2 - javax.annotation javax.annotation-api 1.3.2 + + org.apache.commons + commons-lang3 + 3.8.1 + @@ -148,26 +144,29 @@ - io.projectreactor reactor-test 3.3.5.RELEASE test - org.slf4j slf4j-simple 1.7.25 test + - com.google.code.gson - gson - 2.8.5 - test + com.google.code.findbugs + jsr305 + 3.0.2 + provided @@ -207,6 +206,8 @@ com.fasterxml.jackson.module:jackson-module-parameter-names:[2.10.0] javax.annotation:javax.annotation-api:[1.3.2] org.slf4j:slf4j-simple:[1.7.25] + org.apache.commons:commons-lang3:[3.8.1] + com.google.code.findbugs:jsr305:[3.0.2] diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java index 47548ad5b229..7ce45989023a 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java @@ -2,29 +2,29 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos; -import com.azure.data.cosmos.IndexingMode; +import com.azure.cosmos.models.IndexingMode; /** * Constants class of CosmosDB properties */ public final class Constants { - public static final String DEFAULT_COLLECTION_NAME = ""; - public static final boolean DEFAULT_INDEXINGPOLICY_AUTOMATIC = true; - public static final IndexingMode DEFAULT_INDEXINGPOLICY_MODE = IndexingMode.CONSISTENT; + public static final String DEFAULT_CONTAINER_NAME = ""; + public static final boolean DEFAULT_INDEXING_POLICY_AUTOMATIC = true; + public static final IndexingMode DEFAULT_INDEXING_POLICY_MODE = IndexingMode.CONSISTENT; public static final String DEFAULT_REPOSITORY_IMPLEMENT_POSTFIX = "Impl"; public static final int DEFAULT_TIME_TO_LIVE = -1; // Indicates never expire public static final boolean DEFAULT_AUTO_CREATE_CONTAINER = true; public static final String ID_PROPERTY_NAME = "id"; - public static final String COSMOSDB_MODULE_NAME = "cosmosdb"; - public static final String COSMOSDB_MODULE_PREFIX = "cosmosdb"; + public static final String COSMOS_MODULE_NAME = "cosmosDb"; + public static final String COSMOS_MODULE_PREFIX = "cosmosDb"; public static final String COSMOS_MAPPING_CONTEXT = "cosmosMappingContext"; public static final String USER_AGENT_SUFFIX = "spring-data/"; - public static final String OBJECTMAPPER_BEAN_NAME = "cosmosdbObjectMapper"; + public static final String OBJECT_MAPPER_BEAN_NAME = "cosmosDbObjectMapper"; public static final String ISO_8601_COMPATIBLE_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss:SSSXXX"; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDBFactory.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDBFactory.java new file mode 100644 index 000000000000..4809a439e838 --- /dev/null +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDBFactory.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.spring.data.cosmos; + +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.spring.data.cosmos.common.MacAddress; +import com.azure.spring.data.cosmos.common.PropertyLoader; +import com.azure.spring.data.cosmos.common.TelemetrySender; +import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.lang.NonNull; +import org.springframework.util.Assert; + +import javax.annotation.PostConstruct; +import java.lang.reflect.Field; + +/** + * Factory class for CosmosDb to create client + */ +public class CosmosDBFactory { + + private static final Logger logger = LoggerFactory.getLogger(CosmosDBFactory.class); + + private final CosmosDBConfig config; + + private static final boolean IS_TELEMETRY_ALLOWED = + PropertyLoader.isApplicationTelemetryAllowed(); + + private static final String USER_AGENT_SUFFIX = + Constants.USER_AGENT_SUFFIX + PropertyLoader.getProjectVersion(); + + private String getUserAgentSuffix() { + String suffix = ";" + USER_AGENT_SUFFIX; + + if (IS_TELEMETRY_ALLOWED || config.isAllowTelemetry()) { + suffix += ";" + MacAddress.getHashMac(); + } + + return suffix; + } + + /** + * Validate config and initialization + * + * @param cosmosDBConfig cosmosDBConfig + */ + public CosmosDBFactory(@NonNull CosmosDBConfig cosmosDBConfig) { + validateConfig(cosmosDBConfig); + + this.config = cosmosDBConfig; + } + + /** + * To create a CosmosAsyncClient + * + * @return CosmosClient + */ + public CosmosAsyncClient getCosmosAsyncClient() { + final CosmosClientBuilder cosmosClientBuilderFromConfig = + getCosmosClientBuilderFromConfig(config); + return cosmosClientBuilderFromConfig.buildAsyncClient(); + } + + /** + * To create a CosmosClient + * + * @return CosmosSyncClient + */ + public CosmosClient getCosmosSyncClient() { + final CosmosClientBuilder cosmosClientBuilderFromConfig = + getCosmosClientBuilderFromConfig(config); + return cosmosClientBuilderFromConfig.buildClient(); + } + + private CosmosClientBuilder getCosmosClientBuilderFromConfig(CosmosDBConfig cosmosDBConfig) { + final CosmosClientBuilder cosmosClientBuilder = cosmosDBConfig.getCosmosClientBuilder(); + cosmosClientBuilder.contentResponseOnWriteEnabled(true); + final String userAgentSuffixValue = getUserAgentSuffixValue(cosmosClientBuilder); + final String userAgentSuffix = getUserAgentSuffix() + userAgentSuffixValue; + + return cosmosDBConfig.getCosmosClientBuilder().userAgentSuffix(userAgentSuffix); + } + + private String getUserAgentSuffixValue(CosmosClientBuilder cosmosClientBuilder) { + final Field userAgentSuffix = FieldUtils.getDeclaredField(CosmosClientBuilder.class, + "userAgentSuffix", true); + try { + return (String)userAgentSuffix.get(cosmosClientBuilder); + } catch (IllegalAccessException e) { + logger.error("Error occurred while getting userAgentSuffix from CosmosClientBuilder", + e); + } + return ""; + } + + private void validateConfig(@NonNull CosmosDBConfig config) { + Assert.hasText(config.getDatabase(), "cosmosDb database should have text!"); + } + + @PostConstruct + private void sendTelemetry() { + // If any one of them is enabled, send telemetry data + if (IS_TELEMETRY_ALLOWED || config.isAllowTelemetry()) { + final TelemetrySender sender = new TelemetrySender(); + + sender.send(this.getClass().getSimpleName()); + } + } + + /** + * To get config object of cosmosDb + * + * @return CosmosDBConfig + */ + public CosmosDBConfig getConfig() { + return config; + } +} diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDbFactory.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDbFactory.java deleted file mode 100644 index 9c2d185320a2..000000000000 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDbFactory.java +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.spring.data.cosmos; - -import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.sync.CosmosSyncClient; -import com.azure.spring.data.cosmos.common.MacAddress; -import com.azure.spring.data.cosmos.common.PropertyLoader; -import com.azure.spring.data.cosmos.common.TelemetrySender; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; -import org.springframework.lang.NonNull; - -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -import javax.annotation.PostConstruct; - -/** - * Factory class for cosmosdb to create client - */ -public class CosmosDbFactory { - - private final CosmosDBConfig config; - - private static final boolean IS_TELEMETRY_ALLOWED = PropertyLoader.isApplicationTelemetryAllowed(); - - private static final String USER_AGENT_SUFFIX = Constants.USER_AGENT_SUFFIX + PropertyLoader.getProjectVersion(); - - private String getUserAgentSuffix() { - String suffix = ";" + USER_AGENT_SUFFIX; - - if (IS_TELEMETRY_ALLOWED || config.isAllowTelemetry()) { - suffix += ";" + MacAddress.getHashMac(); - } - - return suffix; - } - - /** - * Validate config and initialization - * - * @param config cosmosdb config - */ - public CosmosDbFactory(@NonNull CosmosDBConfig config) { - validateConfig(config); - - this.config = config; - } - - /** - * To create a CosmosClient - * - * @return CosmosClient - */ - public CosmosClient getCosmosClient() { - final ConnectionPolicy policy = config.getConnectionPolicy(); - final String userAgent = getUserAgentSuffix() + ";" + policy.userAgentSuffix(); - - policy.userAgentSuffix(userAgent); - return CosmosClient.builder() - .endpoint(config.getUri()) - .key(config.getKey()) - .cosmosKeyCredential(config.getCosmosKeyCredential()) - .connectionPolicy(policy) - .consistencyLevel(config.getConsistencyLevel()) - .build(); - } - - /** - * To create a CosmosSyncClient - * - * @return CosmosSyncClient - */ - public CosmosSyncClient getCosmosSyncClient() { - final ConnectionPolicy policy = config.getConnectionPolicy(); - final String userAgent = getUserAgentSuffix() + ";" + policy.userAgentSuffix(); - - policy.userAgentSuffix(userAgent); - return CosmosClient.builder() - .endpoint(config.getUri()) - .key(config.getKey()) - .cosmosKeyCredential(config.getCosmosKeyCredential()) - .connectionPolicy(policy) - .consistencyLevel(config.getConsistencyLevel()) - .buildSyncClient(); - } - - private void validateConfig(@NonNull CosmosDBConfig config) { - Assert.hasText(config.getUri(), "cosmosdb host url should have text!"); - if (config.getCosmosKeyCredential() == null) { - Assert.hasText(config.getKey(), "cosmosdb host key should have text!"); - } else if (StringUtils.isEmpty(config.getKey())) { - Assert.hasText(config.getCosmosKeyCredential().key(), - "cosmosdb credential host key should have text!"); - } - Assert.hasText(config.getDatabase(), "cosmosdb database should have text!"); - Assert.notNull(config.getConnectionPolicy(), "cosmosdb connection policy should not be null!"); - } - - @PostConstruct - private void sendTelemetry() { - // If any one of them is enabled, send telemetry data - if (IS_TELEMETRY_ALLOWED || config.isAllowTelemetry()) { - final TelemetrySender sender = new TelemetrySender(); - - sender.send(this.getClass().getSimpleName()); - } - } - - /** - * To get config object of cosmosdb - * - * @return CosmosDBConfig - */ - public CosmosDBConfig getConfig() { - return config; - } -} diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosdbUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDBUtils.java similarity index 100% rename from sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosdbUtils.java rename to sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDBUtils.java diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java new file mode 100644 index 000000000000..818b683ff9b8 --- /dev/null +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.spring.data.cosmos.common; + +import com.azure.cosmos.CosmosDiagnostics; +import com.azure.cosmos.models.FeedResponse; +import com.azure.spring.data.cosmos.core.ResponseDiagnostics; +import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Util class to fill and process response diagnostics + */ +public class CosmosDBUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(CosmosDBUtils.class); + + /** + * Generate ResponseDiagnostics with cosmos and feed response diagnostics + * + * @param type of cosmosResponse + * @param responseDiagnosticsProcessor collect Response Diagnostics from API responses and + * then set in {@link ResponseDiagnostics} object. + * @param cosmosDiagnostics response from cosmos + * @param feedResponse response from feed + */ + public static void fillAndProcessResponseDiagnostics( + ResponseDiagnosticsProcessor responseDiagnosticsProcessor, + CosmosDiagnostics cosmosDiagnostics, FeedResponse feedResponse) { + if (responseDiagnosticsProcessor == null) { + return; + } + ResponseDiagnostics.CosmosResponseStatistics cosmosResponseStatistics = null; + if (feedResponse != null) { + cosmosResponseStatistics = new ResponseDiagnostics.CosmosResponseStatistics(feedResponse); + } + if (cosmosDiagnostics == null && cosmosResponseStatistics == null) { + LOGGER.debug("Empty response diagnostics"); + return; + } + final ResponseDiagnostics responseDiagnostics = + new ResponseDiagnostics(cosmosDiagnostics, cosmosResponseStatistics); + + // Process response diagnostics + responseDiagnosticsProcessor.processResponseDiagnostics(responseDiagnostics); + } +} diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/TelemetrySender.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/TelemetrySender.java index c57df311ff78..96a34725b379 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/TelemetrySender.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/TelemetrySender.java @@ -4,17 +4,18 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.lang.NonNull; import org.springframework.util.Assert; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.lang.NonNull; + import java.util.HashMap; import java.util.Map; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfiguration.java index cf9b204e4b2d..1885317fc7f6 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfiguration.java @@ -3,90 +3,90 @@ package com.azure.spring.data.cosmos.config; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.sync.CosmosSyncClient; -import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosClient; import com.azure.spring.data.cosmos.Constants; +import com.azure.spring.data.cosmos.CosmosDBFactory; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.ReactiveCosmosTemplate; +import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; +import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * To configure cosmos with client, cosmoscdb factory and template + * To configure cosmos with client, cosmosDB factory and template */ @Configuration public abstract class AbstractCosmosConfiguration extends CosmosConfigurationSupport { /** - * Declare CosmosClient bean. + * Declare CosmosDbFactory bean. * @param config of cosmosDbFactory - * @return CosmosClient bean + * @return CosmosDbFactory bean */ @Bean - public CosmosClient cosmosClient(CosmosDBConfig config) { - return this.cosmosDbFactory(config).getCosmosClient(); + public CosmosDBFactory cosmosDBFactory(CosmosDBConfig config) { + return new CosmosDBFactory(config); } /** - * Declare CosmosSyncClient bean. - * @param config of cosmosDbFactory - * @return CosmosSyncClient bean + * Declare MappingCosmosConverter bean. + * @param cosmosMappingContext cosmosMappingContext + * @return MappingCosmosConverter bean + * @throws ClassNotFoundException if the class type is invalid */ @Bean - public CosmosSyncClient cosmosSyncClient(CosmosDBConfig config) { - return this.cosmosDbFactory(config).getCosmosSyncClient(); + public MappingCosmosConverter mappingCosmosConverter(CosmosMappingContext cosmosMappingContext) throws ClassNotFoundException { + return new MappingCosmosConverter(cosmosMappingContext, objectMapper); } - @Qualifier(Constants.OBJECTMAPPER_BEAN_NAME) - @Autowired(required = false) - private ObjectMapper objectMapper; - /** - * Declare CosmosDbFactory bean. - * @param config of cosmosDbFactory - * @return CosmosDbFactory bean + * Declare CosmosClient bean. + * @param cosmosDBFactory cosmosDbFactory + * @return CosmosClient bean */ @Bean - public CosmosDbFactory cosmosDbFactory(CosmosDBConfig config) { - return new CosmosDbFactory(config); + public CosmosAsyncClient cosmosAsyncClient(CosmosDBFactory cosmosDBFactory) { + return cosmosDBFactory.getCosmosAsyncClient(); } /** - * Declare CosmosTemplate bean. - * @param config of cosmosDbFactory - * @return CosmosTemplate bean - * @throws ClassNotFoundException if the class type is invalid + * Declare CosmosSyncClient bean. + * @param cosmosDBFactory cosmosDBFactory + * @return CosmosSyncClient bean */ @Bean - public CosmosTemplate cosmosTemplate(CosmosDBConfig config) throws ClassNotFoundException { - return new CosmosTemplate(this.cosmosDbFactory(config), this.mappingCosmosConverter(), - config.getDatabase()); + public CosmosClient cosmosClient(CosmosDBFactory cosmosDBFactory) { + return cosmosDBFactory.getCosmosSyncClient(); } + @Qualifier(Constants.OBJECT_MAPPER_BEAN_NAME) + @Autowired(required = false) + private ObjectMapper objectMapper; + /** - * Declare ReactiveCosmosTemplate bean. - * @param config of cosmosDbFactory - * @return ReactiveCosmosTemplate bean - * @throws ClassNotFoundException if the class type is invalid + * Declare CosmosTemplate bean. + * @param cosmosDBFactory cosmosDbFactory + * @param mappingCosmosConverter mappingCosmosConverter + * @return CosmosTemplate bean */ @Bean - public ReactiveCosmosTemplate reactiveCosmosTemplate(CosmosDBConfig config) throws ClassNotFoundException { - return new ReactiveCosmosTemplate(this.cosmosDbFactory(config), this.mappingCosmosConverter(), - config.getDatabase()); + public CosmosTemplate cosmosTemplate(CosmosDBFactory cosmosDBFactory, MappingCosmosConverter mappingCosmosConverter) { + return new CosmosTemplate(cosmosDBFactory, mappingCosmosConverter, cosmosDBFactory.getConfig().getDatabase()); } /** - * Declare MappingCosmosConverter bean. - * @return MappingCosmosConverter bean - * @throws ClassNotFoundException if the class type is invalid + * Declare ReactiveCosmosTemplate bean. + * @param cosmosDBFactory cosmosDbFactory + * @param mappingCosmosConverter mappingCosmosConverter + * @return ReactiveCosmosTemplate bean */ @Bean - public MappingCosmosConverter mappingCosmosConverter() throws ClassNotFoundException { - return new MappingCosmosConverter(this.cosmosMappingContext(), objectMapper); + public ReactiveCosmosTemplate reactiveCosmosTemplate(CosmosDBFactory cosmosDBFactory, MappingCosmosConverter mappingCosmosConverter) { + return new ReactiveCosmosTemplate(cosmosDBFactory, mappingCosmosConverter, cosmosDBFactory.getConfig().getDatabase()); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfigurationSupport.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfigurationSupport.java index 07bd795e99fc..46b240aff9c4 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfigurationSupport.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfigurationSupport.java @@ -3,8 +3,8 @@ package com.azure.spring.data.cosmos.config; -import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; import com.azure.spring.data.cosmos.common.ExpressionResolver; +import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosDBConfig.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosDBConfig.java index 2cab7cb3466c..8c9060d4ec7b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosDBConfig.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosDBConfig.java @@ -2,13 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.config; -import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.CosmosKeyCredential; -import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.cosmos.CosmosClientBuilder; import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; -import org.springframework.util.Assert; import java.beans.ConstructorProperties; @@ -16,96 +11,42 @@ * Config properties of CosmosDB */ public class CosmosDBConfig { - private String uri; - private String key; + private final CosmosClientBuilder cosmosClientBuilder; - private String database; + private final String database; - private ConnectionPolicy connectionPolicy; + private final boolean allowTelemetry; - private ConsistencyLevel consistencyLevel; + private final ResponseDiagnosticsProcessor responseDiagnosticsProcessor; - private boolean allowTelemetry; - - private RequestOptions requestOptions; - - private CosmosKeyCredential cosmosKeyCredential; - - private ResponseDiagnosticsProcessor responseDiagnosticsProcessor; - - private boolean populateQueryMetrics; + private final boolean queryMetricsEnabled; /** * Initialization - * @param uri must not be {@literal null} - * @param key must not be {@literal null} + * @param cosmosClientBuilder must not be {@literal null} * @param database must not be {@literal null} - * @param connectionPolicy must not be {@literal null} - * @param consistencyLevel must not be {@literal null} * @param allowTelemetry must not be {@literal null} - * @param requestOptions must not be {@literal null} - * @param cosmosKeyCredential must not be {@literal null} * @param responseDiagnosticsProcessor must not be {@literal null} - * @param populateQueryMetrics must not be {@literal null} + * @param queryMetricsEnabled must not be {@literal null} */ - @ConstructorProperties({"uri", "key", "database", "connectionPolicy", "consistencyLevel", "allowTelemetry", - "requestOptions", "cosmosKeyCredential", "responseDiagnosticsProcessor", - "populateQueryMetrics"}) - public CosmosDBConfig(String uri, String key, String database, ConnectionPolicy connectionPolicy, - ConsistencyLevel consistencyLevel, boolean allowTelemetry, RequestOptions requestOptions, - CosmosKeyCredential cosmosKeyCredential, - ResponseDiagnosticsProcessor responseDiagnosticsProcessor, boolean populateQueryMetrics) { - this.uri = uri; - this.key = key; + @ConstructorProperties({"cosmosClientBuilder", "database", "allowTelemetry", + "responseDiagnosticsProcessor", "queryMetricsEnabled"}) + public CosmosDBConfig(CosmosClientBuilder cosmosClientBuilder, String database, boolean allowTelemetry, + ResponseDiagnosticsProcessor responseDiagnosticsProcessor, boolean queryMetricsEnabled) { + this.cosmosClientBuilder = cosmosClientBuilder; this.database = database; - this.connectionPolicy = connectionPolicy; - this.consistencyLevel = consistencyLevel; this.allowTelemetry = allowTelemetry; - this.requestOptions = requestOptions; - this.cosmosKeyCredential = cosmosKeyCredential; this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; - this.populateQueryMetrics = populateQueryMetrics; - } - - /** - * Gets uri - * @return uri - */ - public String getUri() { - return uri; - } - - /** - * Gets key - * @return key - */ - public String getKey() { - return key; - } - - /** - * Gets database - * @return database - */ - public String getDatabase() { - return database; - } - - /** - * Gets connection policy - * @return connectionPolicy - */ - public ConnectionPolicy getConnectionPolicy() { - return connectionPolicy; + this.queryMetricsEnabled = queryMetricsEnabled; } /** - * Gets consistency level - * @return ConsistencyLevel + * Gets the cosmos client builder used to build cosmos client + * @return cosmosClientBuilder */ - public ConsistencyLevel getConsistencyLevel() { - return consistencyLevel; + public CosmosClientBuilder getCosmosClientBuilder() { + return cosmosClientBuilder; } /** @@ -116,22 +57,6 @@ public boolean isAllowTelemetry() { return allowTelemetry; } - /** - * Gets request options - * @return RequestOptions - */ - public RequestOptions getRequestOptions() { - return requestOptions; - } - - /** - * Gets Cosmos key credential - * @return CosmosKeyCredential - */ - public CosmosKeyCredential getCosmosKeyCredential() { - return cosmosKeyCredential; - } - /** * Gets response diagnostics processor * @return ResponseDiagnosticsProcessor @@ -141,87 +66,26 @@ public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { } /** - * Checks if is populate query metrics - * @return boolean - */ - public boolean isPopulateQueryMetrics() { - return populateQueryMetrics; - } - - /** - * Sets response diagnostics processor - * @param responseDiagnosticsProcessor must not be {@literal null} - */ - public void setResponseDiagnosticsProcessor(ResponseDiagnosticsProcessor responseDiagnosticsProcessor) { - this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; - } - - /** - * Sets populate query metrics - * @param populateQueryMetrics must not be {@literal null} - */ - public void setPopulateQueryMetrics(boolean populateQueryMetrics) { - this.populateQueryMetrics = populateQueryMetrics; - } - - /** - * create a CosmosDBConfigBuilder with cosmos uri, cosmosKeyCredential and database name - * @param uri must not be {@literal null} - * @param cosmosKeyCredential must not be {@literal null} - * @param database must not be {@literal null} - * @return CosmosDBConfigBuilder - */ - public static CosmosDBConfigBuilder builder(String uri, CosmosKeyCredential cosmosKeyCredential, - String database) { - return defaultBuilder() - .uri(uri) - .cosmosKeyCredential(cosmosKeyCredential) - .database(database) - .connectionPolicy(ConnectionPolicy.defaultPolicy()) - .consistencyLevel(ConsistencyLevel.SESSION) - .requestOptions(new RequestOptions()); - } - - /** - * create a CosmosDBConfigBuilder with cosmos uri, key and database name - * @param uri must not be {@literal null} - * @param key must not be {@literal null} - * @param database must not be {@literal null} - * @return CosmosDBConfigBuilder + * Gets the option to enable query metrics + * @return boolean, whether to enable query metrics */ - public static CosmosDBConfigBuilder builder(String uri, String key, String database) { - return defaultBuilder() - .uri(uri) - .key(key) - .database(database) - .connectionPolicy(ConnectionPolicy.defaultPolicy()) - .consistencyLevel(ConsistencyLevel.SESSION) - .requestOptions(new RequestOptions()); + public boolean isQueryMetricsEnabled() { + return queryMetricsEnabled; } /** - * create a CosmosDBConfigBuilder with connection string and database name - * @param connectionString must not be {@literal null} - * @param database must not be {@literal null} - * @return CosmosDBConfigBuilder - * @throws CosmosDBAccessException for invalid connection string + * Gets the database name + * @return database name */ - public static CosmosDBConfigBuilder builder(String connectionString, String database) { - Assert.hasText(connectionString, "connection string should have text!"); - try { - final String uri = connectionString.split(";")[0].split("=")[1]; - final String key = connectionString.split(";")[1].split("=")[1]; - return builder(uri, key, database); - } catch (ArrayIndexOutOfBoundsException e) { - throw new CosmosDBAccessException("could not parse connection string"); - } + public String getDatabase() { + return database; } /** - * create a CosmosDBConfigBuilder instance + * Create a CosmosDBConfigBuilder instance * @return CosmosDBConfigBuilder */ - public static CosmosDBConfigBuilder defaultBuilder() { + public static CosmosDBConfigBuilder builder() { return new CosmosDBConfigBuilder(); } @@ -229,72 +93,22 @@ public static CosmosDBConfigBuilder defaultBuilder() { * Builder class for cosmos db config */ public static class CosmosDBConfigBuilder { - private String uri; - private String key; private String database; - private ConnectionPolicy connectionPolicy; - private ConsistencyLevel consistencyLevel; + private CosmosClientBuilder cosmosClientBuilder; private boolean allowTelemetry; - private RequestOptions requestOptions; - private CosmosKeyCredential cosmosKeyCredential; private ResponseDiagnosticsProcessor responseDiagnosticsProcessor; - private boolean populateQueryMetrics; + private boolean queryMetricsEnabled; CosmosDBConfigBuilder() { } /** - * Set uri - * - * @param uri value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder uri(String uri) { - this.uri = uri; - return this; - } - - /** - * Set key - * - * @param key value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder key(String key) { - this.key = key; - return this; - } - - /** - * Set database - * - * @param database value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder database(String database) { - this.database = database; - return this; - } - - /** - * Set connectionPolicy - * - * @param connectionPolicy value to initialize + * Set cosmosClientBuilder to use to build cosmos client + * @param cosmosClientBuilder cosmos client builder * @return CosmosDBConfigBuilder */ - public CosmosDBConfigBuilder connectionPolicy(ConnectionPolicy connectionPolicy) { - this.connectionPolicy = connectionPolicy; - return this; - } - - /** - * Set consistencyLevel - * - * @param consistencyLevel value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder consistencyLevel(ConsistencyLevel consistencyLevel) { - this.consistencyLevel = consistencyLevel; + public CosmosDBConfigBuilder cosmosClientBuilder(CosmosClientBuilder cosmosClientBuilder) { + this.cosmosClientBuilder = cosmosClientBuilder; return this; } @@ -310,47 +124,36 @@ public CosmosDBConfigBuilder allowTelemetry(boolean allowTelemetry) { } /** - * Set requestOptions - * - * @param requestOptions value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder requestOptions(RequestOptions requestOptions) { - this.requestOptions = requestOptions; - return this; - } - - /** - * Set cosmosKeyCredential + * Set responseDiagnosticsProcessor * - * @param cosmosKeyCredential value to initialize + * @param responseDiagnosticsProcessor value to initialize * @return CosmosDBConfigBuilder */ - public CosmosDBConfigBuilder cosmosKeyCredential(CosmosKeyCredential cosmosKeyCredential) { - this.cosmosKeyCredential = cosmosKeyCredential; + public CosmosDBConfigBuilder responseDiagnosticsProcessor(ResponseDiagnosticsProcessor + responseDiagnosticsProcessor) { + this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; return this; } /** - * Set responseDiagnosticsProcessor + * Set queryMetricsEnabled * - * @param responseDiagnosticsProcessor value to initialize + * @param queryMetricsEnabled value to initialize * @return CosmosDBConfigBuilder */ - public CosmosDBConfigBuilder responseDiagnosticsProcessor(ResponseDiagnosticsProcessor - responseDiagnosticsProcessor) { - this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; + public CosmosDBConfigBuilder enableQueryMetrics(boolean queryMetricsEnabled) { + this.queryMetricsEnabled = queryMetricsEnabled; return this; } /** - * Set populateQueryMetrics + * Sets the database * - * @param populateQueryMetrics value to initialize + * @param database database name * @return CosmosDBConfigBuilder */ - public CosmosDBConfigBuilder populateQueryMetrics(boolean populateQueryMetrics) { - this.populateQueryMetrics = populateQueryMetrics; + public CosmosDBConfigBuilder database(String database) { + this.database = database; return this; } @@ -360,38 +163,19 @@ public CosmosDBConfigBuilder populateQueryMetrics(boolean populateQueryMetrics) * @return CosmosDBConfig */ public CosmosDBConfig build() { - return new CosmosDBConfig(this.uri, this.key, this.database, this.connectionPolicy, this.consistencyLevel, - this.allowTelemetry, this.requestOptions, this.cosmosKeyCredential, this.responseDiagnosticsProcessor, - this.populateQueryMetrics); + return new CosmosDBConfig(this.cosmosClientBuilder, this.database, this.allowTelemetry, + this.responseDiagnosticsProcessor, this.queryMetricsEnabled); } - /** - * Generate string info of instance - * - * @return String - */ + @Override public String toString() { - return "CosmosDBConfig.CosmosDBConfigBuilder(uri=" - + this.uri - + ", key=" - + this.key - + ", database=" - + this.database - + ", connectionPolicy=" - + this.connectionPolicy - + ", consistencyLevel=" - + this.consistencyLevel - + ", allowTelemetry=" - + this.allowTelemetry - + ", requestOptions=" - + this.requestOptions - + ", cosmosKeyCredential=" - + this.cosmosKeyCredential - + ", responseDiagnosticsProcessor=" - + this.responseDiagnosticsProcessor - + ", populateQueryMetrics=" - + this.populateQueryMetrics - + ")"; + return "CosmosDBConfigBuilder{" + + "database='" + database + '\'' + + ", cosmosClientBuilder=" + cosmosClientBuilder + + ", allowTelemetry=" + allowTelemetry + + ", responseDiagnosticsProcessor=" + responseDiagnosticsProcessor + + ", queryMetricsEnabled=" + queryMetricsEnabled + + '}'; } } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosOperations.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosOperations.java index b723c4d9423e..452d288f2748 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosOperations.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosOperations.java @@ -3,8 +3,8 @@ package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.CosmosContainerProperties; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.query.DocumentQuery; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; @@ -14,35 +14,17 @@ import java.util.List; /** - * Interface for cosmosdb operations + * Interface for cosmosDB operations */ public interface CosmosOperations { /** - * Use getContainerName() instead - * @param domainType class type - * @return container name - * @deprecated Use {@link #getContainerName(Class)} instead - */ - @Deprecated - String getCollectionName(Class domainType); - - /** - * To get container name by domaintype + * To get container name by domainType * @param domainType class type * @return String */ String getContainerName(Class domainType); - /** - * Use createContainerIfNotExists() instead - * @param information cosmos entity information - * @return created container properties - * @deprecated Use {@link #createContainerIfNotExists(CosmosEntityInformation)} instead - */ - @Deprecated - CosmosContainerProperties createCollectionIfNotExists(CosmosEntityInformation information); - /** * Creates container if not exists * @param information CosmosEntityInformation @@ -132,29 +114,26 @@ public interface CosmosOperations { /** * Upserts an item with partition key * @param object upsert object - * @param partitionKey the partition key * @param type of upsert object */ - void upsert(T object, PartitionKey partitionKey); + void upsert(T object); /** * Upserts an item into container with partition key * @param containerName the container name * @param object upsert object - * @param partitionKey the partition key * @param type of upsert object */ - void upsert(String containerName, T object, PartitionKey partitionKey); + void upsert(String containerName, T object); /** * Upserts an item and return item properties * @param containerName the container name * @param object upsert object - * @param partitionKey the partition key * @param type of upsert object * @return upsert object entity */ - T upsertAndReturnEntity(String containerName, T object, PartitionKey partitionKey); + T upsertAndReturnEntity(String containerName, T object); /** * Delete an item by id @@ -169,18 +148,10 @@ public interface CosmosOperations { * Delete all items in a container * * @param containerName the container name - * @param domainType the partition key path + * @param domainType the domainType */ void deleteAll(String containerName, Class domainType); - /** - * Use deleteContainer() instead - * @param containerName container name - * @deprecated Use {@link #deleteContainer(String)} instead. - */ - @Deprecated - void deleteCollection(String containerName); - /** * Delete container * @@ -194,7 +165,7 @@ public interface CosmosOperations { * @param query the document query * @param domainType type class * @param containerName the container name - * @param type class of domaintype + * @param type class of domainType * @return deleted items in a List */ List delete(DocumentQuery query, Class domainType, String containerName); @@ -205,7 +176,7 @@ public interface CosmosOperations { * @param query the document query * @param domainType type class * @param containerName the container name - * @param type class of domaintype + * @param type class of domainType * @return found results in a List */ List find(DocumentQuery query, Class domainType, String containerName); @@ -249,7 +220,7 @@ public interface CosmosOperations { * @param query the document query * @param domainType type class * @param containerName the container name - * @param type class of domaintype + * @param type class of domainType * @return Page */ Page paginationQuery(DocumentQuery query, Class domainType, String containerName); @@ -266,12 +237,11 @@ public interface CosmosOperations { * Count * * @param query the document query - * @param domainType the domain type * @param containerName the container name - * @param type class of domaintype + * @param type class of domainType * @return count result */ - long count(DocumentQuery query, Class domainType, String containerName); + long count(DocumentQuery query, String containerName); /** * To get converter diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java index 7b0043ca791b..425000bf9436 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java @@ -3,20 +3,20 @@ package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.CosmosItemResponse; -import com.azure.data.cosmos.AccessCondition; -import com.azure.data.cosmos.AccessConditionType; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.CosmosItemRequestOptions; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosContainerProperties; -import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosDatabase; -import com.azure.data.cosmos.PartitionKey; -import com.azure.spring.data.cosmos.common.CosmosdbUtils; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosAsyncContainer; +import com.azure.cosmos.CosmosAsyncDatabase; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosContainerResponse; +import com.azure.cosmos.models.CosmosItemRequestOptions; +import com.azure.cosmos.models.CosmosItemResponse; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.FeedResponse; +import com.azure.cosmos.models.PartitionKey; +import com.azure.cosmos.models.SqlQuerySpec; +import com.azure.cosmos.models.ThroughputProperties; +import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.common.CosmosDBUtils; import com.azure.spring.data.cosmos.common.Memoizer; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.generator.CountQueryGenerator; @@ -28,7 +28,7 @@ import com.azure.spring.data.cosmos.core.query.DocumentQuery; import com.azure.spring.data.cosmos.exception.CosmosDBExceptionUtils; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.fasterxml.jackson.databind.JsonNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; @@ -56,24 +56,23 @@ public class CosmosTemplate implements CosmosOperations, ApplicationContextAware private static final Logger LOGGER = LoggerFactory.getLogger(CosmosTemplate.class); - private static final String COUNT_VALUE_KEY = "_aggregate"; - private final MappingCosmosConverter mappingCosmosConverter; private final String databaseName; private final ResponseDiagnosticsProcessor responseDiagnosticsProcessor; - private final boolean isPopulateQueryMetrics; + private final boolean enableQueryMetrics; - private final CosmosClient cosmosClient; + private final CosmosAsyncClient cosmosAsyncClient; private final Function, CosmosEntityInformation> entityInfoCreator = - Memoizer.memoize(this::getCosmosEntityInformation); + Memoizer.memoize(this::getCosmosEntityInformation); /** * Initialization - * @param cosmosDbFactory must not be {@literal null} + * + * @param cosmosDbFactory must not be {@literal null} * @param mappingCosmosConverter must not be {@literal null} - * @param dbName must not be {@literal null} + * @param dbName must not be {@literal null} */ - public CosmosTemplate(CosmosDbFactory cosmosDbFactory, + public CosmosTemplate(CosmosDBFactory cosmosDbFactory, MappingCosmosConverter mappingCosmosConverter, String dbName) { Assert.notNull(cosmosDbFactory, "CosmosDbFactory must not be null!"); @@ -82,13 +81,15 @@ public CosmosTemplate(CosmosDbFactory cosmosDbFactory, this.mappingCosmosConverter = mappingCosmosConverter; this.databaseName = dbName; - this.cosmosClient = cosmosDbFactory.getCosmosClient(); - this.responseDiagnosticsProcessor = cosmosDbFactory.getConfig().getResponseDiagnosticsProcessor(); - this.isPopulateQueryMetrics = cosmosDbFactory.getConfig().isPopulateQueryMetrics(); + this.cosmosAsyncClient = cosmosDbFactory.getCosmosAsyncClient(); + this.responseDiagnosticsProcessor = + cosmosDbFactory.getConfig().getResponseDiagnosticsProcessor(); + this.enableQueryMetrics = cosmosDbFactory.getConfig().isQueryMetricsEnabled(); } /** * Sets the application context + * * @param applicationContext must not be {@literal null} * @throws BeansException the bean exception */ @@ -96,11 +97,11 @@ public void setApplicationContext(ApplicationContext applicationContext) throws } /** - * * Inserts item + * * @param objectToSave must not be {@literal null} * @param partitionKey must not be {@literal null} - * @param type class of domain type + * @param type class of domain type * @return the inserted item */ public T insert(T objectToSave, PartitionKey partitionKey) { @@ -111,46 +112,50 @@ public T insert(T objectToSave, PartitionKey partitionKey) { /** * Inserts item into the given container + * * @param containerName must not be {@literal null} - * @param objectToSave must not be {@literal null} - * @param partitionKey must not be {@literal null} - * @param type class of domain type + * @param objectToSave must not be {@literal null} + * @param partitionKey must not be {@literal null} + * @param type class of domain type * @return the inserted item */ public T insert(String containerName, T objectToSave, PartitionKey partitionKey) { - Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only " + + "whitespaces"); Assert.notNull(objectToSave, "objectToSave should not be null"); - final CosmosItemProperties originalItem = mappingCosmosConverter.writeCosmosItemProperties(objectToSave); + final JsonNode originalItem = + mappingCosmosConverter.writeJsonNode(objectToSave); - LOGGER.debug("execute createItem in database {} container {}", this.databaseName, containerName); + LOGGER.debug("execute createItem in database {} container {}", this.databaseName, + containerName); final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.partitionKey(partitionKey); - @SuppressWarnings("unchecked") - final Class domainType = (Class) objectToSave.getClass(); + @SuppressWarnings("unchecked") final Class domainType = + (Class)objectToSave.getClass(); - final CosmosItemResponse response = cosmosClient + final CosmosItemResponse response = cosmosAsyncClient .getDatabase(this.databaseName) .getContainer(containerName) - .createItem(originalItem, options) + .createItem(originalItem, partitionKey, options) .doOnNext(cosmosItemResponse -> - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null)) + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to insert item", throwable)) .block(); assert response != null; - return mappingCosmosConverter.read(domainType, response.properties()); + return toDomainObject(domainType, response.getItem()); } /** * Finds item by id - * @param id must not be {@literal null} + * + * @param id must not be {@literal null} * @param domainType must not be {@literal null} - * @param type class of domain type + * @param type class of domain type * @return found item */ public T findById(Object id, Class domainType) { @@ -166,16 +171,14 @@ public T findById(Object id, Class domainType, PartitionKey partitionKey) assertValidId(id); final String containerName = getContainerName(domainType); - return cosmosClient + return cosmosAsyncClient .getDatabase(databaseName) .getContainer(containerName) - .getItem(id.toString(), partitionKey) - .read() + .readItem(id.toString(), partitionKey, JsonNode.class) .flatMap(cosmosItemResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null); - return Mono.justOrEmpty(toDomainObject(domainType, - cosmosItemResponse.properties())); + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return Mono.justOrEmpty(toDomainObject(domainType, cosmosItemResponse.getItem())); }) .onErrorResume(throwable -> CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) @@ -184,32 +187,35 @@ public T findById(Object id, Class domainType, PartitionKey partitionKey) /** * Finds item by id + * * @param containerName must not be {@literal null} - * @param id must not be {@literal null} - * @param domainType must not be {@literal null} - * @param type class of domain type + * @param id must not be {@literal null} + * @param domainType must not be {@literal null} + * @param type class of domain type * @return found item */ public T findById(String containerName, Object id, Class domainType) { - Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only " + + "whitespaces"); Assert.notNull(domainType, "domainType should not be null"); assertValidId(id); - final String query = String.format("select * from root where root.id = '%s'", id.toString()); - final FeedOptions options = new FeedOptions(); - options.enableCrossPartitionQuery(true); - options.populateQueryMetrics(isPopulateQueryMetrics); - return cosmosClient + final String query = String.format("select * from root where root.id = '%s'", + id.toString()); + final CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); + options.setQueryMetricsEnabled(enableQueryMetrics); + return cosmosAsyncClient .getDatabase(databaseName) .getContainer(containerName) - .queryItems(query, options) + .queryItems(query, options, JsonNode.class) + .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, cosmosItemFeedResponse); + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Mono.justOrEmpty(cosmosItemFeedResponse - .results() + .getResults() .stream() - .map(cosmosItem -> mappingCosmosConverter.read(domainType, cosmosItem)) + .map(cosmosItem -> toDomainObject(domainType, cosmosItem)) .findFirst()); }) .onErrorResume(throwable -> @@ -219,68 +225,69 @@ public T findById(String containerName, Object id, Class domainType) { /** * Upserts an item with partition key + * * @param object upsert object - * @param partitionKey the partition key - * @param type of upsert object + * @param type of upsert object */ - public void upsert(T object, PartitionKey partitionKey) { + public void upsert(T object) { Assert.notNull(object, "Upsert object should not be null"); - upsert(getContainerName(object.getClass()), object, partitionKey); + upsert(getContainerName(object.getClass()), object); } /** * Upserts an item into container with partition key + * * @param containerName the container name - * @param object upsert object - * @param partitionKey the partition key - * @param type of upsert object + * @param object upsert object + * @param type of upsert object */ - public void upsert(String containerName, T object, PartitionKey partitionKey) { - upsertAndReturnEntity(containerName, object, partitionKey); + public void upsert(String containerName, T object) { + upsertAndReturnEntity(containerName, object); } /** * Upserts an item and return item properties + * * @param containerName the container name - * @param object upsert object - * @param partitionKey the partition key - * @param type of upsert object + * @param object upsert object + * @param type of upsert object * @return upsert object entity */ - public T upsertAndReturnEntity(String containerName, T object, PartitionKey partitionKey) { - Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); + public T upsertAndReturnEntity(String containerName, T object) { + Assert.hasText(containerName, "containerName should not be null, empty or only " + + "whitespaces"); Assert.notNull(object, "Upsert object should not be null"); - final CosmosItemProperties originalItem = mappingCosmosConverter.writeCosmosItemProperties(object); + final JsonNode originalItem = mappingCosmosConverter.writeJsonNode(object); - LOGGER.debug("execute upsert item in database {} container {}", this.databaseName, containerName); + LOGGER.debug("execute upsert item in database {} container {}", this.databaseName, + containerName); - @SuppressWarnings("unchecked") - final Class domainType = (Class) object.getClass(); + @SuppressWarnings("unchecked") final Class domainType = (Class)object.getClass(); final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.partitionKey(partitionKey); applyVersioning(domainType, originalItem, options); - final CosmosItemResponse cosmosItemResponse = cosmosClient + final CosmosItemResponse cosmosItemResponse = cosmosAsyncClient .getDatabase(this.databaseName) .getContainer(containerName) .upsertItem(originalItem, options) - .doOnNext(response -> CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - response, null)) - .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to upsert item", throwable)) + .doOnNext(response -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + response.getDiagnostics(), null)) + .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to upsert" + + " item", throwable)) .block(); assert cosmosItemResponse != null; - return mappingCosmosConverter.read(domainType, cosmosItemResponse.properties()); + return toDomainObject(domainType, cosmosItemResponse.getItem()); } /** * Find the DocumentQuery, find all the items specified by domain type. * * @param domainType the domain type - * @param class type of domain + * @param class type of domain * @return found results in a List */ public List findAll(Class domainType) { @@ -293,20 +300,21 @@ public List findAll(Class domainType) { * Find the DocumentQuery, find all the items specified by domain type in the given container. * * @param containerName the container name - * @param domainType the domain type - * @param class type of domain + * @param domainType the domain type + * @param class type of domain * @return found results in a List */ public List findAll(String containerName, final Class domainType) { - Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only " + + "whitespaces"); Assert.notNull(domainType, "domainType should not be null"); final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)); - final List items = findItems(query, domainType, containerName); + final List items = findItems(query, containerName); return items.stream() - .map(d -> getConverter().read(domainType, d)) - .collect(Collectors.toList()); + .map(d -> toDomainObject(domainType, d)) + .collect(Collectors.toList()); } @Override @@ -316,20 +324,21 @@ public List findAll(PartitionKey partitionKey, final Class domainType) final String containerName = getContainerName(domainType); - final FeedOptions feedOptions = new FeedOptions(); - feedOptions.partitionKey(partitionKey); - feedOptions.populateQueryMetrics(isPopulateQueryMetrics); + final CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); + cosmosQueryRequestOptions.setPartitionKey(partitionKey); + cosmosQueryRequestOptions.setQueryMetricsEnabled(enableQueryMetrics); - return cosmosClient + return cosmosAsyncClient .getDatabase(this.databaseName) .getContainer(containerName) - .readAllItems(feedOptions) + .queryItems("SELECT * FROM r", cosmosQueryRequestOptions, JsonNode.class) + .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, cosmosItemFeedResponse); - return Flux.fromIterable(cosmosItemFeedResponse.results()); + return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) - .map(cosmosItemProperties -> toDomainObject(domainType, cosmosItemProperties)) + .map(jsonNode -> toDomainObject(domainType, jsonNode)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to find items", throwable)) .collectList() @@ -340,41 +349,31 @@ public List findAll(PartitionKey partitionKey, final Class domainType) * Delete the DocumentQuery, delete all the items in the given container. * * @param containerName Container name of database - * @param domainType the domain type + * @param domainType the domain type */ public void deleteAll(@NonNull String containerName, @NonNull Class domainType) { - Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only " + + "whitespaces"); final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)); this.delete(query, domainType, containerName); } - @Override - public void deleteCollection(@NonNull String containerName) { - deleteContainer(containerName); - } - @Override public void deleteContainer(@NonNull String containerName) { Assert.hasText(containerName, "containerName should have text."); - cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .delete() - .doOnNext(response -> CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - response, null)) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete container", throwable)) - .block(); - } - - /** - * To get collection name by domaintype - * @param domainType class type - * @return String - */ - public String getCollectionName(Class domainType) { - return getContainerName(domainType); + cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .delete() + .doOnNext(response -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + response.getDiagnostics(), null); + }) + .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to delete " + + "container", + throwable)) + .block(); } @Override @@ -384,45 +383,48 @@ public String getContainerName(Class domainType) { return entityInfoCreator.apply(domainType).getContainerName(); } - @Override - public CosmosContainerProperties createCollectionIfNotExists(@NonNull CosmosEntityInformation information) { - return createContainerIfNotExists(information); - } - @Override public CosmosContainerProperties createContainerIfNotExists(CosmosEntityInformation information) { - final CosmosContainerResponse response = cosmosClient + final CosmosContainerResponse response = cosmosAsyncClient .createDatabaseIfNotExists(this.databaseName) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to create database", throwable)) .flatMap(cosmosDatabaseResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosDatabaseResponse, null); - final CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties( - information.getContainerName(), "/" + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosDatabaseResponse.getDiagnostics(), null); + final CosmosContainerProperties cosmosContainerProperties = + new CosmosContainerProperties( + information.getContainerName(), "/" + information.getPartitionKeyFieldName()); - cosmosContainerProperties.defaultTimeToLive(information.getTimeToLive()); - cosmosContainerProperties.indexingPolicy(information.getIndexingPolicy()); - - CosmosDatabase database = cosmosDatabaseResponse.database(); - Mono mono = null; - + cosmosContainerProperties.setDefaultTimeToLiveInSeconds(information.getTimeToLive()); + cosmosContainerProperties.setIndexingPolicy(information.getIndexingPolicy()); + + CosmosAsyncDatabase cosmosAsyncDatabase = cosmosAsyncClient + .getDatabase(cosmosDatabaseResponse.getProperties().getId()); + Mono cosmosContainerResponseMono; + if (information.getRequestUnit() == null) { - mono = database.createContainerIfNotExists(cosmosContainerProperties); + cosmosContainerResponseMono = + cosmosAsyncDatabase.createContainerIfNotExists(cosmosContainerProperties); } else { - mono = database.createContainerIfNotExists(cosmosContainerProperties, information.getRequestUnit()); + ThroughputProperties throughputProperties = + ThroughputProperties.createManualThroughput(information.getRequestUnit()); + cosmosContainerResponseMono = + cosmosAsyncDatabase.createContainerIfNotExists(cosmosContainerProperties, + throughputProperties); } - - return mono + + return cosmosContainerResponseMono .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to create container", throwable)) + CosmosDBExceptionUtils.exceptionHandler("Failed to create container", + throwable)) .doOnNext(cosmosContainerResponse -> - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosContainerResponse, null)); + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosContainerResponse.getDiagnostics(), null)); }) .block(); assert response != null; - return response.properties(); + return response.getProperties(); } /** @@ -430,29 +432,29 @@ public CosmosContainerProperties createContainerIfNotExists(CosmosEntityInformat * from the result. * * @param containerName Container name of database - * @param id item id - * @param partitionKey the paritition key + * @param id item id + * @param partitionKey the partition key */ public void deleteById(String containerName, Object id, PartitionKey partitionKey) { - Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only " + + "whitespaces"); assertValidId(id); - LOGGER.debug("execute deleteById in database {} container {}", this.databaseName, containerName); + LOGGER.debug("execute deleteById in database {} container {}", this.databaseName, + containerName); if (partitionKey == null) { - partitionKey = PartitionKey.None; + partitionKey = PartitionKey.NONE; } - final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.partitionKey(partitionKey); - cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .getItem(id.toString(), partitionKey) - .delete(options) - .doOnNext(response -> CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - response, null)) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", throwable)) - .block(); + cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .deleteItem(id.toString(), partitionKey) + .doOnNext(response -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + response.getDiagnostics(), null)) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", + throwable)) + .block(); } @Override @@ -462,72 +464,75 @@ public List findByIds(Iterable ids, Class domainType, String c Assert.hasText(containerName, "container should not be null, empty or only whitespaces"); final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.IN, "id", - Collections.singletonList(ids))); + Collections.singletonList(ids))); return find(query, domainType, containerName); } /** * Finds the document query items - * @param query The representation for query method. - * @param domainType Class of domain + * + * @param query The representation for query method. + * @param domainType Class of domain * @param containerName Container name of database - * @param class of domainType + * @param class of domainType * @return All the found items as List. */ - public List find(@NonNull DocumentQuery query, @NonNull Class domainType, String containerName) { + public List find(@NonNull DocumentQuery query, @NonNull Class domainType, + String containerName) { Assert.notNull(query, "DocumentQuery should not be null."); Assert.notNull(domainType, "domainType should not be null."); Assert.hasText(containerName, "container should not be null, empty or only whitespaces"); - return findItems(query, domainType, containerName) - .stream() - .map(cosmosItemProperties -> toDomainObject(domainType, cosmosItemProperties)) - .collect(Collectors.toList()); + final List items = findItems(query, containerName); + return items.stream() + .map(d -> toDomainObject(domainType, d)) + .collect(Collectors.toList()); } /** * Checks if document query items exist - * @param query The representation for query method. - * @param domainType Class of domain + * + * @param query The representation for query method. + * @param domainType Class of domain * @param containerName Container name of database - * @param class of domainType + * @param class of domainType * @return if items exist */ - public Boolean exists(@NonNull DocumentQuery query, @NonNull Class domainType, String containerName) { - return this.find(query, domainType, containerName).size() > 0; + public Boolean exists(@NonNull DocumentQuery query, @NonNull Class domainType, + String containerName) { + return this.count(query, containerName) > 0; } /** * Delete the DocumentQuery, need to query the domains at first, then delete the item * from the result. - * The cosmosdb Sql API do _NOT_ support DELETE query, we cannot add one DeleteQueryGenerator. + * The cosmos db Sql API do _NOT_ support DELETE query, we cannot add one DeleteQueryGenerator. * - * @param query The representation for query method. - * @param domainType Class of domain + * @param query The representation for query method. + * @param domainType Class of domain * @param containerName Container name of database - * @param class of domainType + * @param class of domainType * @return All the deleted items as List. */ @Override public List delete(@NonNull DocumentQuery query, @NonNull Class domainType, - @NonNull String containerName) { + @NonNull String containerName) { Assert.notNull(query, "DocumentQuery should not be null."); Assert.notNull(domainType, "domainType should not be null."); Assert.hasText(containerName, "container should not be null, empty or only whitespaces"); - final List results = findItems(query, domainType, containerName); + final List results = findItems(query, containerName); final List partitionKeyName = getPartitionKeyNames(domainType); - return results.stream().map(cosmosItemProperties -> { - final CosmosItemResponse cosmosItemResponse = deleteItem(cosmosItemProperties, - partitionKeyName, containerName, domainType); - return getConverter().read(domainType, cosmosItemResponse.properties()); - }).collect(Collectors.toList()); + return results.stream() + .map(item -> deleteItem(item, partitionKeyName, containerName, domainType)) + .collect(Collectors.toList()); } @Override public Page findAll(Pageable pageable, Class domainType, String containerName) { - final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)).with(pageable); + final DocumentQuery query = + new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)).with(pageable); if (pageable.getSort().isSorted()) { query.with(pageable.getSort()); } @@ -536,56 +541,64 @@ public Page findAll(Pageable pageable, Class domainType, String contai } @Override - public Page paginationQuery(DocumentQuery query, Class domainType, String containerName) { - Assert.isTrue(query.getPageable().getPageSize() > 0, "pageable should have page size larger than 0"); + public Page paginationQuery(DocumentQuery query, Class domainType, + String containerName) { + Assert.isTrue(query.getPageable().getPageSize() > 0, "pageable should have page size " + + "larger than 0"); Assert.hasText(containerName, "container should not be null, empty or only whitespaces"); final Pageable pageable = query.getPageable(); - final FeedOptions feedOptions = new FeedOptions(); + final CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); + cosmosQueryRequestOptions.setQueryMetricsEnabled(enableQueryMetrics); + + CosmosAsyncContainer container = + cosmosAsyncClient.getDatabase(this.databaseName).getContainer(containerName); + final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(query); + + Flux> feedResponseFlux; if (pageable instanceof CosmosPageRequest) { - feedOptions.requestContinuation(((CosmosPageRequest) pageable).getRequestContinuation()); + feedResponseFlux = container + .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) + .byPage(((CosmosPageRequest)pageable).getRequestContinuation(), + pageable.getPageSize()); + } else { + feedResponseFlux = container + .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) + .byPage(pageable.getPageSize()); } - feedOptions.maxItemCount(pageable.getPageSize()); - feedOptions.enableCrossPartitionQuery(query.isCrossPartitionQuery(getPartitionKeyNames(domainType))); - feedOptions.populateQueryMetrics(isPopulateQueryMetrics); - - final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(query); - final FeedResponse feedResponse = cosmosClient - .getDatabase(this.databaseName) - .getContainer(containerName) - .queryItems(sqlQuerySpec, feedOptions) + final FeedResponse feedResponse = feedResponseFlux .doOnNext(propertiesFeedResponse -> - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, propertiesFeedResponse)) + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + propertiesFeedResponse.getCosmosDiagnostics(), propertiesFeedResponse)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to query items", throwable)) .next() .block(); assert feedResponse != null; - final Iterator it = feedResponse.results().iterator(); + final Iterator it = feedResponse.getResults().iterator(); final List result = new ArrayList<>(); for (int index = 0; it.hasNext() - && index < pageable.getPageSize(); index++) { + && index < pageable.getPageSize(); index++) { - final CosmosItemProperties cosmosItemProperties = it.next(); - if (cosmosItemProperties == null) { + final JsonNode jsonNode = it.next(); + if (jsonNode == null) { continue; } - final T entity = mappingCosmosConverter.read(domainType, cosmosItemProperties); + final T entity = mappingCosmosConverter.read(domainType, jsonNode); result.add(entity); } - final long total = count(query, domainType, containerName); + final long total = count(query, containerName); final int contentSize = result.size(); int pageSize; if (contentSize < pageable.getPageSize() - && contentSize > 0) { + && contentSize > 0) { // If the content size is less than page size, // this means, cosmosDB is returning less items than page size, // because of either RU limit, or payload limit @@ -599,7 +612,7 @@ public Page paginationQuery(DocumentQuery query, Class domainType, Str final CosmosPageRequest pageRequest = CosmosPageRequest.of(pageable.getOffset(), pageable.getPageNumber(), pageSize, - feedResponse.continuationToken(), + feedResponse.getContinuationToken(), query.getSort()); return new CosmosPageImpl<>(result, pageRequest, total); @@ -610,19 +623,16 @@ public long count(String containerName) { Assert.hasText(containerName, "container name should not be empty"); final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)); - final Long count = getCountValue(query, true, containerName); + final Long count = getCountValue(query, containerName); assert count != null; return count; } @Override - public long count(DocumentQuery query, Class domainType, String containerName) { - Assert.notNull(domainType, "domainType should not be null"); + public long count(DocumentQuery query, String containerName) { Assert.hasText(containerName, "container name should not be empty"); - final boolean isCrossPartitionQuery = - query.isCrossPartitionQuery(getPartitionKeyNames(domainType)); - final Long count = getCountValue(query, isCrossPartitionQuery, containerName); + final Long count = getCountValue(query, containerName); assert count != null; return count; } @@ -632,30 +642,31 @@ public MappingCosmosConverter getConverter() { return this.mappingCosmosConverter; } - private Long getCountValue(DocumentQuery query, boolean isCrossPartitionQuery, String containerName) { + private Long getCountValue(DocumentQuery query, String containerName) { final SqlQuerySpec querySpec = new CountQueryGenerator().generateCosmos(query); - final FeedOptions options = new FeedOptions(); - - options.enableCrossPartitionQuery(isCrossPartitionQuery); - options.populateQueryMetrics(isPopulateQueryMetrics); + final CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); + options.setQueryMetricsEnabled(enableQueryMetrics); return executeQuery(querySpec, containerName, options) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to get count value", throwable)) - .doOnNext(response -> CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, response)) - .next() - .map(r -> r.results().get(0).getLong(COUNT_VALUE_KEY)) - .block(); + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to get count value", throwable)) + .doOnNext(response -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + null, response)) + .next() + .map(r -> r.getResults().get(0).asLong()) + .block(); } - private Flux> executeQuery(SqlQuerySpec sqlQuerySpec, String containerName, - FeedOptions options) { - return cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .queryItems(sqlQuerySpec, options) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to execute query", throwable)); + private Flux> executeQuery(SqlQuerySpec sqlQuerySpec, + String containerName, + CosmosQueryRequestOptions options) { + return cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .queryItems(sqlQuerySpec, options, JsonNode.class) + .byPage() + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to execute " + + "query", throwable)); } private List getPartitionKeyNames(Class domainType) { @@ -675,76 +686,70 @@ private void assertValidId(Object id) { } } - private List findItems(@NonNull DocumentQuery query, - @NonNull Class domainType, - @NonNull String containerName) { + private List findItems(@NonNull DocumentQuery query, + @NonNull String containerName) { final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(query); - final boolean isCrossPartitionQuery = - query.isCrossPartitionQuery(getPartitionKeyNames(domainType)); - final FeedOptions feedOptions = new FeedOptions(); - feedOptions.enableCrossPartitionQuery(isCrossPartitionQuery); - feedOptions.populateQueryMetrics(isPopulateQueryMetrics); - - return cosmosClient - .getDatabase(this.databaseName) - .getContainer(containerName) - .queryItems(sqlQuerySpec, feedOptions) - .flatMap(cosmosItemFeedResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, cosmosItemFeedResponse); - return Flux.fromIterable(cosmosItemFeedResponse.results()); - }) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to find items", throwable)) - .collectList() - .block(); - } - - private CosmosItemResponse deleteItem(@NonNull CosmosItemProperties cosmosItemProperties, - @NonNull List partitionKeyNames, - String containerName, - @NonNull Class domainType) { + final CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); + cosmosQueryRequestOptions.setQueryMetricsEnabled(enableQueryMetrics); + + return cosmosAsyncClient + .getDatabase(this.databaseName) + .getContainer(containerName) + .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) + .byPage() + .flatMap(cosmosItemFeedResponse -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); + return Flux.fromIterable(cosmosItemFeedResponse.getResults()); + }) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to find items", throwable)) + .collectList() + .block(); + } + + private T deleteItem(@NonNull JsonNode jsonNode, + @NonNull List partitionKeyNames, + String containerName, + @NonNull Class domainType) { Assert.isTrue(partitionKeyNames.size() <= 1, "Only one Partition is supported."); PartitionKey partitionKey = null; if (!partitionKeyNames.isEmpty() - && StringUtils.hasText(partitionKeyNames.get(0))) { - partitionKey = new PartitionKey(cosmosItemProperties.get(partitionKeyNames.get(0))); + && StringUtils.hasText(partitionKeyNames.get(0))) { + partitionKey = new PartitionKey(jsonNode.get(partitionKeyNames.get(0)).asText()); } if (partitionKey == null) { - partitionKey = PartitionKey.None; + partitionKey = PartitionKey.NONE; } - final CosmosItemRequestOptions options = new CosmosItemRequestOptions(partitionKey); - applyVersioning(domainType, cosmosItemProperties, options); + final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + applyVersioning(domainType, jsonNode, options); - return cosmosClient + return cosmosAsyncClient .getDatabase(this.databaseName) .getContainer(containerName) - .getItem(cosmosItemProperties.id(), partitionKey) - .delete(options) - .doOnNext(response -> CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - response, null)) + .deleteItem(jsonNode.get("id").asText(), partitionKey) + .doOnNext(response -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + response.getDiagnostics(), null)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", throwable)) + .flatMap(objectCosmosItemResponse -> Mono.just(toDomainObject(domainType, jsonNode))) .block(); } - private T toDomainObject(@NonNull Class domainType, CosmosItemProperties cosmosItemProperties) { - return mappingCosmosConverter.read(domainType, cosmosItemProperties); + private T toDomainObject(@NonNull Class domainType, JsonNode responseJsonNode) { + return mappingCosmosConverter.read(domainType, responseJsonNode); } private void applyVersioning(Class domainType, - CosmosItemProperties cosmosItemProperties, - CosmosItemRequestOptions options) { + JsonNode jsonNode, + CosmosItemRequestOptions options) { if (entityInfoCreator.apply(domainType).isVersioned()) { - final AccessCondition accessCondition = new AccessCondition(); - accessCondition.type(AccessConditionType.IF_MATCH); - accessCondition.condition(cosmosItemProperties.etag()); - options.accessCondition(accessCondition); + options.setIfMatchETag(jsonNode.get("_etag").asText()); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosOperations.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosOperations.java index 04b4a447db3c..fd47cffba210 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosOperations.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosOperations.java @@ -3,8 +3,8 @@ package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.CosmosContainerResponse; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.query.DocumentQuery; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; @@ -24,15 +24,6 @@ public interface ReactiveCosmosOperations { */ String getContainerName(Class domainType); - /** - * Use createContainerIfNotExists() instead - * @param information cosmos entity information - * @return Mono of cosmos container response - * @deprecated use {@link #createContainerIfNotExists(CosmosEntityInformation)} instead. - */ - @Deprecated - Mono createCollectionIfNotExists(CosmosEntityInformation information); - /** * Creates a container if it doesn't already exist * @@ -124,25 +115,23 @@ public interface ReactiveCosmosOperations { Mono insert(String containerName, Object objectToSave, PartitionKey partitionKey); /** - * Upsert + * Upsert an item with partition key * * @param object the object to upsert - * @param partitionKey the partition key * @param type class of object * @return Mono */ - Mono upsert(T object, PartitionKey partitionKey); + Mono upsert(T object); /** - * Upsert + * Upsert an item to container with partition key * * @param containerName the container name * @param object the object to save - * @param partitionKey the partition key * @param type class of object * @return Mono */ - Mono upsert(String containerName, T object, PartitionKey partitionKey); + Mono upsert(String containerName, T object); /** * Delete an item by id @@ -158,10 +147,10 @@ public interface ReactiveCosmosOperations { * Delete all items in a container * * @param containerName the container name - * @param partitionKey the partition key path + * @param domainType the domainType * @return void Mono */ - Mono deleteAll(String containerName, String partitionKey); + Mono deleteAll(String containerName, Class domainType); /** * Delete container diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java index b2e0204aed11..fef7e40ec9a6 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java @@ -3,19 +3,18 @@ package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.AccessCondition; -import com.azure.data.cosmos.AccessConditionType; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.CosmosItemRequestOptions; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosContainerProperties; -import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosDatabase; -import com.azure.data.cosmos.PartitionKey; -import com.azure.spring.data.cosmos.common.CosmosdbUtils; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosAsyncDatabase; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.CosmosContainerResponse; +import com.azure.cosmos.models.CosmosItemRequestOptions; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.FeedResponse; +import com.azure.cosmos.models.PartitionKey; +import com.azure.cosmos.models.SqlQuerySpec; +import com.azure.cosmos.models.ThroughputProperties; +import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.common.CosmosDBUtils; import com.azure.spring.data.cosmos.common.Memoizer; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.generator.CountQueryGenerator; @@ -25,7 +24,7 @@ import com.azure.spring.data.cosmos.core.query.DocumentQuery; import com.azure.spring.data.cosmos.exception.CosmosDBExceptionUtils; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.fasterxml.jackson.databind.JsonNode; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -45,28 +44,25 @@ */ @SuppressWarnings("unchecked") public class ReactiveCosmosTemplate implements ReactiveCosmosOperations, ApplicationContextAware { - private static final String COUNT_VALUE_KEY = "_aggregate"; private final MappingCosmosConverter mappingCosmosConverter; private final String databaseName; - private final CosmosClient cosmosClient; + private final CosmosAsyncClient cosmosAsyncClient; private final ResponseDiagnosticsProcessor responseDiagnosticsProcessor; private final boolean isPopulateQueryMetrics; private final Function, CosmosEntityInformation> entityInfoCreator = Memoizer.memoize(this::getCosmosEntityInformation); - private final List containerNameCache; - /** * Constructor * - * @param cosmosDbFactory the cosmosdbfactory + * @param cosmosDbFactory the cosmos db factory * @param mappingCosmosConverter the mappingCosmosConverter - * @param dbName database name + * @param dbName database name */ - public ReactiveCosmosTemplate(CosmosDbFactory cosmosDbFactory, + public ReactiveCosmosTemplate(CosmosDBFactory cosmosDbFactory, MappingCosmosConverter mappingCosmosConverter, String dbName) { Assert.notNull(cosmosDbFactory, "CosmosDbFactory must not be null!"); @@ -74,11 +70,11 @@ public ReactiveCosmosTemplate(CosmosDbFactory cosmosDbFactory, this.mappingCosmosConverter = mappingCosmosConverter; this.databaseName = dbName; - this.containerNameCache = new ArrayList<>(); - this.cosmosClient = cosmosDbFactory.getCosmosClient(); - this.responseDiagnosticsProcessor = cosmosDbFactory.getConfig().getResponseDiagnosticsProcessor(); - this.isPopulateQueryMetrics = cosmosDbFactory.getConfig().isPopulateQueryMetrics(); + this.cosmosAsyncClient = cosmosDbFactory.getCosmosAsyncClient(); + this.responseDiagnosticsProcessor = + cosmosDbFactory.getConfig().getResponseDiagnosticsProcessor(); + this.isPopulateQueryMetrics = cosmosDbFactory.getConfig().isQueryMetricsEnabled(); } /** @@ -89,17 +85,6 @@ public void setApplicationContext(@NonNull ApplicationContext applicationContext // NOTE: When application context instance variable gets introduced, assign it here. } - /** - * Creates a container if it doesn't already exist - * - * @param information the CosmosEntityInformation - * @return Mono containing CosmosContainerResponse - */ - @Override - public Mono createCollectionIfNotExists(CosmosEntityInformation information) { - return createContainerIfNotExists(information); - } - /** * Creates a container if it doesn't already exist * @@ -109,37 +94,44 @@ public Mono createCollectionIfNotExists(CosmosEntityInf @Override public Mono createContainerIfNotExists(CosmosEntityInformation information) { - return cosmosClient + return cosmosAsyncClient .createDatabaseIfNotExists(this.databaseName) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to create database", throwable)) .flatMap(cosmosDatabaseResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosDatabaseResponse, null); - final CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties( - information.getContainerName(), - "/" + information.getPartitionKeyFieldName()); - cosmosContainerProperties.defaultTimeToLive(information.getTimeToLive()); - cosmosContainerProperties.indexingPolicy(information.getIndexingPolicy()); - - CosmosDatabase database = cosmosDatabaseResponse.database(); - Mono mono = null; - + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosDatabaseResponse.getDiagnostics(), null); + final CosmosContainerProperties cosmosContainerProperties = + new CosmosContainerProperties( + information.getContainerName(), + "/" + information.getPartitionKeyFieldName()); + cosmosContainerProperties.setDefaultTimeToLiveInSeconds(information.getTimeToLive()); + cosmosContainerProperties.setIndexingPolicy(information.getIndexingPolicy()); + + CosmosAsyncDatabase database = + cosmosAsyncClient.getDatabase(cosmosDatabaseResponse.getProperties().getId()); + Mono cosmosContainerResponseMono; + if (information.getRequestUnit() == null) { - mono = database.createContainerIfNotExists(cosmosContainerProperties); + cosmosContainerResponseMono = + database.createContainerIfNotExists(cosmosContainerProperties); } else { - mono = database.createContainerIfNotExists(cosmosContainerProperties, information.getRequestUnit()); + ThroughputProperties throughputProperties = + ThroughputProperties.createManualThroughput(information.getRequestUnit()); + cosmosContainerResponseMono = + database.createContainerIfNotExists(cosmosContainerProperties, + throughputProperties); } - - return mono + + return cosmosContainerResponseMono .map(cosmosContainerResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosContainerResponse, null); - this.containerNameCache.add(information.getContainerName()); + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosContainerResponse.getDiagnostics(), null); return cosmosContainerResponse; }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to create container", throwable)); + CosmosDBExceptionUtils.exceptionHandler("Failed to create container", + throwable)); }); } @@ -148,7 +140,7 @@ public Mono createContainerIfNotExists(CosmosEntityInfo * Find all items in a given container * * @param containerName the containerName - * @param domainType the domainType + * @param domainType the domainType * @return Flux with all the found items or error */ @Override @@ -176,18 +168,19 @@ public Flux findAll(PartitionKey partitionKey, Class domainType) { final String containerName = getContainerName(domainType); - final FeedOptions feedOptions = new FeedOptions(); - feedOptions.partitionKey(partitionKey); - feedOptions.populateQueryMetrics(isPopulateQueryMetrics); + final CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); + cosmosQueryRequestOptions.setPartitionKey(partitionKey); + cosmosQueryRequestOptions.setQueryMetricsEnabled(isPopulateQueryMetrics); - return cosmosClient + return cosmosAsyncClient .getDatabase(this.databaseName) .getContainer(containerName) - .readAllItems(feedOptions) + .queryItems("SELECT * FROM r", cosmosQueryRequestOptions, JsonNode.class) + .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, cosmosItemFeedResponse); - return Flux.fromIterable(cosmosItemFeedResponse.results()); + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); + return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) .map(cosmosItemProperties -> toDomainObject(domainType, cosmosItemProperties)) .onErrorResume(throwable -> @@ -197,7 +190,7 @@ public Flux findAll(PartitionKey partitionKey, Class domainType) { /** * Find by id * - * @param id the id + * @param id the id * @param domainType the domainType * @return Mono with the item or error */ @@ -210,44 +203,48 @@ public Mono findById(Object id, Class domainType) { /** * Find by id * - * @param containerName the containername - * @param id the id - * @param domainType the entity class + * @param containerName the container name + * @param id the id + * @param domainType the entity class * @return Mono with the item or error */ @Override public Mono findById(String containerName, Object id, Class domainType) { - Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only " + + "whitespaces"); Assert.notNull(domainType, "domainType should not be null"); assertValidId(id); - final String query = String.format("select * from root where root.id = '%s'", id.toString()); - final FeedOptions options = new FeedOptions(); - options.enableCrossPartitionQuery(true); - options.populateQueryMetrics(isPopulateQueryMetrics); - - return cosmosClient.getDatabase(databaseName) - .getContainer(containerName) - .queryItems(query, options) - .flatMap(cosmosItemFeedResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, cosmosItemFeedResponse); - return Mono.justOrEmpty(cosmosItemFeedResponse - .results() - .stream() - .map(cosmosItem -> toDomainObject(domainType, cosmosItem)) - .findFirst()); - }) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) - .next(); + final String query = String.format("select * from root where root.id = '%s'", + id.toString()); + final CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); + options.setQueryMetricsEnabled(isPopulateQueryMetrics); + + return cosmosAsyncClient.getDatabase(databaseName) + .getContainer(containerName) + .queryItems(query, options, JsonNode.class) + .byPage() + .flatMap(cosmosItemFeedResponse -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemFeedResponse.getCosmosDiagnostics(), + cosmosItemFeedResponse); + return Mono.justOrEmpty(cosmosItemFeedResponse + .getResults() + .stream() + .map(cosmosItem -> toDomainObject(domainType, cosmosItem)) + .findFirst()); + }) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to " + + "find item", throwable)) + .next(); } /** * Find by id * - * @param id the id - * @param domainType the entity class + * @param id the id + * @param domainType the entity class * @param partitionKey partition Key * @return Mono with the item or error */ @@ -257,24 +254,24 @@ public Mono findById(Object id, Class domainType, PartitionKey partiti assertValidId(id); final String containerName = getContainerName(domainType); - return cosmosClient.getDatabase(databaseName) - .getContainer(containerName) - .getItem(id.toString(), partitionKey) - .read() - .flatMap(cosmosItemResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null); - return Mono.justOrEmpty(toDomainObject(domainType, - cosmosItemResponse.properties())); - }) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)); + return cosmosAsyncClient.getDatabase(databaseName) + .getContainer(containerName) + .readItem(id.toString(), partitionKey, JsonNode.class) + .flatMap(cosmosItemResponse -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return Mono.justOrEmpty(toDomainObject(domainType, + cosmosItemResponse.getItem())); + }) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to " + + "find item", throwable)); } /** * Insert * - * @param type of inserted objectToSave + * @param type of inserted objectToSave * @param objectToSave the object to save * @param partitionKey the partition key * @return Mono with the item or error @@ -289,178 +286,158 @@ public Mono insert(T objectToSave, PartitionKey partitionKey) { * Insert * * @param objectToSave the object to save - * @param type of inserted objectToSave + * @param type of inserted objectToSave * @return Mono with the item or error */ public Mono insert(T objectToSave) { Assert.notNull(objectToSave, "objectToSave should not be null"); - final Class domainType = (Class) objectToSave.getClass(); - final CosmosItemProperties originalItem = mappingCosmosConverter.writeCosmosItemProperties(objectToSave); - return cosmosClient.getDatabase(this.databaseName) - .getContainer(getContainerName(objectToSave.getClass())) - .createItem(originalItem, new CosmosItemRequestOptions()) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to insert item", throwable)) - .flatMap(cosmosItemResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null); - return Mono.just(toDomainObject(domainType, cosmosItemResponse.properties())); - }); + final Class domainType = (Class)objectToSave.getClass(); + final JsonNode originalItem = + mappingCosmosConverter.writeJsonNode(objectToSave); + return cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(getContainerName(objectToSave.getClass())) + .createItem(originalItem, new CosmosItemRequestOptions()) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to insert " + + "item", throwable)) + .flatMap(cosmosItemResponse -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return Mono.just(toDomainObject(domainType, + cosmosItemResponse.getItem())); + }); } /** * Insert * - * @param type of inserted objectToSave + * @param type of inserted objectToSave * @param containerName the container name - * @param objectToSave the object to save - * @param partitionKey the partition key + * @param objectToSave the object to save + * @param partitionKey the partition key * @return Mono with the item or error */ - public Mono insert(String containerName, Object objectToSave, PartitionKey partitionKey) { - Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); + public Mono insert(String containerName, Object objectToSave, + PartitionKey partitionKey) { + Assert.hasText(containerName, "containerName should not be null, empty or only " + + "whitespaces"); Assert.notNull(objectToSave, "objectToSave should not be null"); - final Class domainType = (Class) objectToSave.getClass(); - final CosmosItemProperties originalItem = mappingCosmosConverter.writeCosmosItemProperties(objectToSave); + final Class domainType = (Class)objectToSave.getClass(); + final JsonNode originalItem = + mappingCosmosConverter.writeJsonNode(objectToSave); final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - if (partitionKey != null) { - options.partitionKey(partitionKey); + if (partitionKey == null) { + partitionKey = PartitionKey.NONE; } - return cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .createItem(originalItem, options) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to insert item", throwable)) - .flatMap(cosmosItemResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null); - return Mono.just(toDomainObject(domainType, cosmosItemResponse.properties())); - }); + return cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .createItem(originalItem, partitionKey, options) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to insert " + + "item", throwable)) + .flatMap(cosmosItemResponse -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return Mono.just(toDomainObject(domainType, + cosmosItemResponse.getItem())); + }); } /** * Upsert * * @param object the object to upsert - * @param partitionKey the partition key * @return Mono with the item or error */ @Override - public Mono upsert(T object, PartitionKey partitionKey) { - return upsert(getContainerName(object.getClass()), object, partitionKey); + public Mono upsert(T object) { + return upsert(getContainerName(object.getClass()), object); } /** * Upsert * * @param containerName the container name - * @param object the object to save - * @param partitionKey the partition key + * @param object the object to save * @return Mono with the item or error */ @Override - public Mono upsert(String containerName, T object, PartitionKey partitionKey) { - final Class domainType = (Class) object.getClass(); - final CosmosItemProperties originalItem = mappingCosmosConverter.writeCosmosItemProperties(object); + public Mono upsert(String containerName, T object) { + final Class domainType = (Class)object.getClass(); + final JsonNode originalItem = + mappingCosmosConverter.writeJsonNode(object); final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - if (partitionKey != null) { - options.partitionKey(partitionKey); - } applyVersioning(object.getClass(), originalItem, options); - return cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .upsertItem(originalItem, options) - .flatMap(cosmosItemResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null); - return Mono.just(toDomainObject(domainType, cosmosItemResponse.properties())); - }) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to upsert item", throwable)); + return cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .upsertItem(originalItem, options) + .flatMap(cosmosItemResponse -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return Mono.just(toDomainObject(domainType, + cosmosItemResponse.getItem())); + }) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to upsert " + + "item", throwable)); } /** * Delete an item by id * * @param containerName the container name - * @param id the id - * @param partitionKey the partition key + * @param id the id + * @param partitionKey the partition key * @return void Mono */ @Override public Mono deleteById(String containerName, Object id, PartitionKey partitionKey) { - Assert.hasText(containerName, "container name should not be null, empty or only whitespaces"); + Assert.hasText(containerName, "container name should not be null, empty or only " + + "whitespaces"); assertValidId(id); if (partitionKey == null) { - partitionKey = PartitionKey.None; + partitionKey = PartitionKey.NONE; } - final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.partitionKey(partitionKey); - return cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .getItem(id.toString(), partitionKey) - .delete(options) - .doOnNext(cosmosItemResponse -> - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null)) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", throwable)) - .then(); + return cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .deleteItem(id.toString(), partitionKey) + .doOnNext(cosmosItemResponse -> + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null)) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to delete " + + "item", throwable)) + .then(); } /** * Delete all items in a container * * @param containerName the container name - * @param partitionKeyName the partition key path + * @param domainType the domainType * @return void Mono */ @Override - public Mono deleteAll(String containerName, String partitionKeyName) { - Assert.hasText(containerName, "container name should not be null, empty or only whitespaces"); - Assert.notNull(partitionKeyName, "partitionKeyName should not be null"); + public Mono deleteAll(@NonNull String containerName, @NonNull Class domainType) { + Assert.hasText(containerName, "container name should not be null, empty or only " + + "whitespaces"); - final Criteria criteria = Criteria.getInstance(CriteriaType.ALL); - final DocumentQuery query = new DocumentQuery(criteria); - final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(query); - final FeedOptions options = new FeedOptions(); - final boolean isCrossPartitionQuery = query.isCrossPartitionQuery(Collections.singletonList(partitionKeyName)); - options.enableCrossPartitionQuery(isCrossPartitionQuery); - options.populateQueryMetrics(isPopulateQueryMetrics); - return cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .queryItems(sqlQuerySpec, options) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to query items", throwable)) - .flatMap(cosmosItemFeedResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, cosmosItemFeedResponse); - return Flux.fromIterable(cosmosItemFeedResponse.results()); - }) - .flatMap(cosmosItemProperties -> cosmosClient - .getDatabase(this.databaseName) - .getContainer(containerName) - .getItem(cosmosItemProperties.id(), cosmosItemProperties.get(partitionKeyName)) - .delete() - .doOnNext(cosmosItemResponse -> - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null)) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete items", throwable))) - .then(); + final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)); + + return this.delete(query, domainType, containerName).then(); } /** * Delete items matching query * - * @param query the document query - * @param domainType the entity class + * @param query the document query + * @param domainType the entity class * @param containerName the container name * @return Mono */ @@ -468,52 +445,53 @@ public Mono deleteAll(String containerName, String partitionKeyName) { public Flux delete(DocumentQuery query, Class domainType, String containerName) { Assert.notNull(query, "DocumentQuery should not be null."); Assert.notNull(domainType, "domainType should not be null."); - Assert.hasText(containerName, "container name should not be null, empty or only whitespaces"); + Assert.hasText(containerName, "container name should not be null, empty or only " + + "whitespaces"); - final Flux results = findItems(query, domainType, containerName); + final Flux results = findItems(query, containerName); final List partitionKeyName = getPartitionKeyNames(domainType); - return results.flatMap(d -> deleteItem(d, partitionKeyName, containerName, domainType)) - .flatMap(cosmosItemProperties -> Mono.just(toDomainObject(domainType, cosmosItemProperties))); + return results.flatMap(d -> deleteItem(d, partitionKeyName, containerName, domainType)); } /** * Find items * - * @param query the document query - * @param domainType the entity class + * @param query the document query + * @param domainType the entity class * @param containerName the container name * @return Flux with found items or error */ @Override public Flux find(DocumentQuery query, Class domainType, String containerName) { - return findItems(query, domainType, containerName) - .map(cosmosItemProperties -> toDomainObject(domainType, cosmosItemProperties)); + return findItems(query, containerName) + .map(cosmosItemProperties -> toDomainObject(domainType, cosmosItemProperties)); } /** * Exists * - * @param query the document query - * @param domainType the entity class + * @param query the document query + * @param domainType the entity class * @param containerName the container name * @return Mono with a boolean or error */ @Override public Mono exists(DocumentQuery query, Class domainType, String containerName) { - return count(query, true, containerName).flatMap(count -> Mono.just(count > 0)); + return count(query, containerName).flatMap(count -> Mono.just(count > 0)); } /** * Exists - * @param id the id - * @param domainType the entity class - * @param containerName the containercontainer nam,e + * + * @param id the id + * @param domainType the entity class + * @param containerName the container name * @return Mono with a boolean or error */ public Mono existsById(Object id, Class domainType, String containerName) { return findById(containerName, id, domainType) - .flatMap(o -> Mono.just(o != null)); + .flatMap(o -> Mono.just(o != null)); } /** @@ -525,19 +503,19 @@ public Mono existsById(Object id, Class domainType, String container @Override public Mono count(String containerName) { final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)); - return count(query, true, containerName); + return count(query, containerName); } /** * Count * - * @param query the document query + * @param query the document query * @param containerName the container name * @return Mono with count or error */ @Override public Mono count(DocumentQuery query, String containerName) { - return count(query, true, containerName); + return getCountValue(query, containerName); } @Override @@ -545,42 +523,32 @@ public MappingCosmosConverter getConverter() { return mappingCosmosConverter; } - /** - *Count - * - * @param query the document query - * @param isCrossPartitionQuery flag of cross partition - * @param containerName the container name - * @return Mono - */ - public Mono count(DocumentQuery query, boolean isCrossPartitionQuery, String containerName) { - return getCountValue(query, isCrossPartitionQuery, containerName); - } - - private Mono getCountValue(DocumentQuery query, boolean isCrossPartitionQuery, String containerName) { + private Mono getCountValue(DocumentQuery query, String containerName) { final SqlQuerySpec querySpec = new CountQueryGenerator().generateCosmos(query); - final FeedOptions options = new FeedOptions(); + final CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); - options.enableCrossPartitionQuery(isCrossPartitionQuery); - options.populateQueryMetrics(isPopulateQueryMetrics); + options.setQueryMetricsEnabled(isPopulateQueryMetrics); return executeQuery(querySpec, containerName, options) - .doOnNext(feedResponse -> CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, feedResponse)) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to get count value", throwable)) - .next() - .map(r -> r.results().get(0).getLong(COUNT_VALUE_KEY)); + .doOnNext(feedResponse -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + null, feedResponse)) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to get count value", throwable)) + .next() + .map(r -> r.getResults().get(0).asLong()); } - private Flux> executeQuery(SqlQuerySpec sqlQuerySpec, String containerName, - FeedOptions options) { + private Flux> executeQuery(SqlQuerySpec sqlQuerySpec, + String containerName, + CosmosQueryRequestOptions options) { - return cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .queryItems(sqlQuerySpec, options) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to execute query", throwable)); + return cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .queryItems(sqlQuerySpec, options, JsonNode.class) + .byPage() + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to execute " + + "query", throwable)); } /** @@ -591,16 +559,16 @@ private Flux> executeQuery(SqlQuerySpec sqlQu @Override public void deleteContainer(@NonNull String containerName) { Assert.hasText(containerName, "containerName should have text."); - cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .delete() - .doOnNext(cosmosContainerResponse -> - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosContainerResponse, null)) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete container", throwable)) - .block(); - this.containerNameCache.remove(containerName); + cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .delete() + .doOnNext(cosmosContainerResponse -> + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosContainerResponse.getDiagnostics(), null)) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to delete container" + , throwable)) + .block(); } /** @@ -613,25 +581,24 @@ public String getContainerName(Class domainType) { return entityInfoCreator.apply(domainType).getContainerName(); } - private Flux findItems(@NonNull DocumentQuery query, @NonNull Class domainType, - @NonNull String containerName) { + private Flux findItems(@NonNull DocumentQuery query, + @NonNull String containerName) { final SqlQuerySpec sqlQuerySpec = new FindQuerySpecGenerator().generateCosmos(query); - final boolean isCrossPartitionQuery = query.isCrossPartitionQuery(getPartitionKeyNames(domainType)); - final FeedOptions feedOptions = new FeedOptions(); - feedOptions.enableCrossPartitionQuery(isCrossPartitionQuery); - feedOptions.populateQueryMetrics(isPopulateQueryMetrics); - - return cosmosClient - .getDatabase(this.databaseName) - .getContainer(containerName) - .queryItems(sqlQuerySpec, feedOptions) - .flatMap(cosmosItemFeedResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - null, cosmosItemFeedResponse); - return Flux.fromIterable(cosmosItemFeedResponse.results()); - }) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to query items", throwable)); + final CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); + cosmosQueryRequestOptions.setQueryMetricsEnabled(isPopulateQueryMetrics); + + return cosmosAsyncClient + .getDatabase(this.databaseName) + .getContainer(containerName) + .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) + .byPage() + .flatMap(cosmosItemFeedResponse -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + null, cosmosItemFeedResponse); + return Flux.fromIterable(cosmosItemFeedResponse.getResults()); + }) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to query items", throwable)); } private void assertValidId(Object id) { @@ -651,48 +618,46 @@ private List getPartitionKeyNames(Class domainType) { return Collections.singletonList(entityInfo.getPartitionKeyFieldName()); } - private Mono deleteItem(@NonNull CosmosItemProperties cosmosItemProperties, - @NonNull List partitionKeyNames, - String containerName, - @NonNull Class domainType) { + private Mono deleteItem(@NonNull JsonNode jsonNode, + @NonNull List partitionKeyNames, + String containerName, + @NonNull Class domainType) { Assert.isTrue(partitionKeyNames.size() <= 1, "Only one Partition is supported."); PartitionKey partitionKey = null; if (!partitionKeyNames.isEmpty() - && StringUtils.hasText(partitionKeyNames.get(0))) { - partitionKey = new PartitionKey(cosmosItemProperties.get(partitionKeyNames.get(0))); + && StringUtils.hasText(partitionKeyNames.get(0))) { + partitionKey = new PartitionKey(jsonNode.get(partitionKeyNames.get(0)).asText()); } - final CosmosItemRequestOptions options = new CosmosItemRequestOptions(partitionKey); - applyVersioning(domainType, cosmosItemProperties, options); + final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + applyVersioning(domainType, jsonNode, options); - return cosmosClient.getDatabase(this.databaseName) - .getContainer(containerName) - .getItem(cosmosItemProperties.id(), partitionKey) - .delete(options) - .map(cosmosItemResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosItemResponse, null); - return cosmosItemProperties; - }) - .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", throwable)); + return cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(containerName) + .deleteItem(jsonNode.get("id").asText(), partitionKey) + .map(cosmosItemResponse -> { + CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return cosmosItemResponse; + }) + .flatMap(objectCosmosItemResponse -> Mono.just(toDomainObject(domainType, jsonNode))) + .onErrorResume(throwable -> + CosmosDBExceptionUtils.exceptionHandler("Failed to delete " + + "item", throwable)); } - private T toDomainObject(@NonNull Class domainType, CosmosItemProperties cosmosItemProperties) { - return mappingCosmosConverter.read(domainType, cosmosItemProperties); + private T toDomainObject(@NonNull Class domainType, JsonNode jsonNode) { + return mappingCosmosConverter.read(domainType, jsonNode); } private void applyVersioning(Class domainType, - CosmosItemProperties cosmosItemProperties, + JsonNode jsonNode, CosmosItemRequestOptions options) { if (entityInfoCreator.apply(domainType).isVersioned()) { - final AccessCondition accessCondition = new AccessCondition(); - accessCondition.type(AccessConditionType.IF_MATCH); - accessCondition.condition(cosmosItemProperties.etag()); - options.accessCondition(accessCondition); + options.setIfMatchETag(jsonNode.get("_etag").asText()); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnostics.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnostics.java index c5c990c6b66d..ee59400a293f 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnostics.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnostics.java @@ -3,81 +3,50 @@ package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.CosmosResponseDiagnostics; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.FeedResponseDiagnostics; -import com.azure.data.cosmos.Resource; +import com.azure.cosmos.CosmosDiagnostics; +import com.azure.cosmos.models.FeedResponse; /** * Diagnostics class of cosmos and feed response */ public class ResponseDiagnostics { - private CosmosResponseDiagnostics cosmosResponseDiagnostics; - private FeedResponseDiagnostics feedResponseDiagnostics; + private CosmosDiagnostics cosmosDiagnostics; private CosmosResponseStatistics cosmosResponseStatistics; /** * Initialization * - * @param cosmosResponseDiagnostics cannot be null - * @param feedResponseDiagnostics cannot be null - */ - public ResponseDiagnostics(CosmosResponseDiagnostics cosmosResponseDiagnostics, - FeedResponseDiagnostics feedResponseDiagnostics) { - this.cosmosResponseDiagnostics = cosmosResponseDiagnostics; - this.feedResponseDiagnostics = feedResponseDiagnostics; - } - - /** - * Initialization - * - * @param cosmosResponseDiagnostics cannot be null - * @param feedResponseDiagnostics cannot be null + * @param cosmosDiagnostics cannot be null * @param cosmosResponseStatistics cannot be null */ - public ResponseDiagnostics(CosmosResponseDiagnostics cosmosResponseDiagnostics, - FeedResponseDiagnostics feedResponseDiagnostics, + public ResponseDiagnostics(CosmosDiagnostics cosmosDiagnostics, CosmosResponseStatistics cosmosResponseStatistics) { - this.cosmosResponseDiagnostics = cosmosResponseDiagnostics; - this.feedResponseDiagnostics = feedResponseDiagnostics; + this.cosmosDiagnostics = cosmosDiagnostics; this.cosmosResponseStatistics = cosmosResponseStatistics; } /** * To get diagnostics of cosmos response + * * @return CosmosResponseDiagnostics */ - public CosmosResponseDiagnostics getCosmosResponseDiagnostics() { - return cosmosResponseDiagnostics; + public CosmosDiagnostics getCosmosDiagnostics() { + return cosmosDiagnostics; } /** * To set diagnostics of cosmos response - * @param cosmosResponseDiagnostics cannot be null - */ - public void setCosmosResponseDiagnostics(CosmosResponseDiagnostics cosmosResponseDiagnostics) { - this.cosmosResponseDiagnostics = cosmosResponseDiagnostics; - } - - /** - * To get diagnostics of feed response - * @return FeedResponseDiagnostics - */ - public FeedResponseDiagnostics getFeedResponseDiagnostics() { - return feedResponseDiagnostics; - } - - /** - * To set diagnostics of feed response - * @param feedResponseDiagnostics cannot be null + * + * @param cosmosDiagnostics cannot be null */ - public void setFeedResponseDiagnostics(FeedResponseDiagnostics feedResponseDiagnostics) { - this.feedResponseDiagnostics = feedResponseDiagnostics; + public void setCosmosDiagnostics(CosmosDiagnostics cosmosDiagnostics) { + this.cosmosDiagnostics = cosmosDiagnostics; } /** * To get the statistics value of cosmos response + * * @return CosmosResponseStatistics */ public CosmosResponseStatistics getCosmosResponseStatistics() { @@ -86,6 +55,7 @@ public CosmosResponseStatistics getCosmosResponseStatistics() { /** * To set statistics of cosmos response + * * @param cosmosResponseStatistics cannot be null */ public void setCosmosResponseStatistics(CosmosResponseStatistics cosmosResponseStatistics) { @@ -95,17 +65,9 @@ public void setCosmosResponseStatistics(CosmosResponseStatistics cosmosResponseS @Override public String toString() { final StringBuilder diagnostics = new StringBuilder(); - if (cosmosResponseDiagnostics != null) { + if (cosmosDiagnostics != null) { diagnostics.append("cosmosResponseDiagnostics={") - .append(cosmosResponseDiagnostics) - .append("}"); - } - if (feedResponseDiagnostics != null) { - if (diagnostics.length() != 0) { - diagnostics.append(", "); - } - diagnostics.append("feedResponseDiagnostics={") - .append(feedResponseDiagnostics) + .append(cosmosDiagnostics) .append("}"); } if (cosmosResponseStatistics != null) { @@ -131,15 +93,16 @@ public static class CosmosResponseStatistics { * Initialization * * @param feedResponse response from feed - * @param type of cosmosResponse + * @param type of cosmosResponse */ - public CosmosResponseStatistics(FeedResponse feedResponse) { - this.requestCharge = feedResponse.requestCharge(); - this.activityId = feedResponse.activityId(); + public CosmosResponseStatistics(FeedResponse feedResponse) { + this.requestCharge = feedResponse.getRequestCharge(); + this.activityId = feedResponse.getActivityId(); } /** * To get the charge value of request + * * @return double */ public double getRequestCharge() { @@ -148,6 +111,7 @@ public double getRequestCharge() { /** * To get the activity id + * * @return String */ public String getActivityId() { @@ -157,11 +121,8 @@ public String getActivityId() { @Override public String toString() { return "CosmosResponseStatistics{" - + "requestCharge=" - + requestCharge - + ", activityId='" - + activityId - + '\'' + + "requestCharge=" + requestCharge + "," + + "activityId='" + activityId + '\'' + '}'; } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnosticsProcessor.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnosticsProcessor.java index 1eb96b409809..577dc47e2a16 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnosticsProcessor.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnosticsProcessor.java @@ -3,10 +3,10 @@ package com.azure.spring.data.cosmos.core; -import javax.annotation.Nullable; +import org.springframework.lang.Nullable; /** - * Interface for processing cosmosdb response + * Interface for processing cosmosDB response */ public interface ResponseDiagnosticsProcessor { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/convert/MappingCosmosConverter.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/convert/MappingCosmosConverter.java index 8fae263e43d5..94c927e1eef8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/convert/MappingCosmosConverter.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/convert/MappingCosmosConverter.java @@ -2,14 +2,14 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.convert; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentProperty; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentEntity; +import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentProperty; import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; -import org.json.JSONObject; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -22,7 +22,6 @@ import org.springframework.data.mapping.model.ConvertingPropertyAccessor; import org.springframework.util.Assert; -import java.io.IOException; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; @@ -32,26 +31,26 @@ /** * A converter class between common types and cosmosItemProperties */ -@SuppressWarnings("unchecked") public class MappingCosmosConverter - implements EntityConverter, CosmosPersistentProperty, - Object, CosmosItemProperties>, + implements EntityConverter, CosmosPersistentProperty, Object, + JsonNode>, ApplicationContextAware { protected final MappingContext, - CosmosPersistentProperty> mappingContext; + CosmosPersistentProperty> mappingContext; protected GenericConversionService conversionService; private ApplicationContext applicationContext; private final ObjectMapper objectMapper; /** * Initialization + * * @param mappingContext must not be {@literal null} - * @param objectMapper must not be {@literal null} + * @param objectMapper must not be {@literal null} */ public MappingCosmosConverter( MappingContext, CosmosPersistentProperty> mappingContext, - @Qualifier(Constants.OBJECTMAPPER_BEAN_NAME) ObjectMapper objectMapper) { + @Qualifier(Constants.OBJECT_MAPPER_BEAN_NAME) ObjectMapper objectMapper) { this.mappingContext = mappingContext; this.conversionService = new GenericConversionService(); this.objectMapper = objectMapper == null ? ObjectMapperFactory.getObjectMapper() @@ -59,54 +58,48 @@ public MappingCosmosConverter( } @Override - public R read(Class type, CosmosItemProperties cosmosItemProperties) { - if (cosmosItemProperties == null) { - return null; - } + public R read(Class type, JsonNode jsonNode) { final CosmosPersistentEntity entity = mappingContext.getPersistentEntity(type); Assert.notNull(entity, "Entity is null."); - return readInternal(entity, type, cosmosItemProperties); + return readInternal(entity, type, jsonNode); } - private R readInternal(final CosmosPersistentEntity entity, Class type, - final CosmosItemProperties cosmosItemProperties) { + @Override + public void write(Object source, JsonNode sink) { + throw new UnsupportedOperationException("The feature is not implemented yet"); + } + private R readInternal(final CosmosPersistentEntity entity, Class type, + final JsonNode jsonNode) { + final ObjectNode objectNode = jsonNode.deepCopy(); try { final CosmosPersistentProperty idProperty = entity.getIdProperty(); - final Object idValue = cosmosItemProperties.id(); - final JSONObject jsonObject = new JSONObject(cosmosItemProperties.toJson()); - + final JsonNode idValue = jsonNode.get("id"); if (idProperty != null) { // Replace the key id to the actual id field name in domain - jsonObject.remove(Constants.ID_PROPERTY_NAME); - jsonObject.put(idProperty.getName(), idValue); + objectNode.remove(Constants.ID_PROPERTY_NAME); + objectNode.set(idProperty.getName(), idValue); } - - return objectMapper.readValue(jsonObject.toString(), type); - } catch (IOException e) { + return objectMapper.treeToValue(objectNode, type); + } catch (JsonProcessingException e) { throw new IllegalStateException("Failed to read the source document " - + cosmosItemProperties.toJson() + + objectNode.toPrettyString() + " to target type " + type, e); } } - @Override - @Deprecated - public void write(Object sourceEntity, CosmosItemProperties document) { - throw new UnsupportedOperationException("The feature is not implemented yet"); - } - /** * To write source entity as a cosmos item + * * @param sourceEntity must not be {@literal null} * @return CosmosItemProperties - * @throws MappingException no mapping metadata for entity type + * @throws MappingException no mapping metadata for entity type * @throws CosmosDBAccessException fail to map document value */ - public CosmosItemProperties writeCosmosItemProperties(Object sourceEntity) { + public JsonNode writeJsonNode(Object sourceEntity) { if (sourceEntity == null) { return null; } @@ -121,11 +114,11 @@ public CosmosItemProperties writeCosmosItemProperties(Object sourceEntity) { final ConvertingPropertyAccessor accessor = getPropertyAccessor(sourceEntity); final CosmosPersistentProperty idProperty = persistentEntity.getIdProperty(); - final CosmosItemProperties cosmosItemProperties; + final ObjectNode cosmosObjectNode; try { - cosmosItemProperties = - new CosmosItemProperties(objectMapper.writeValueAsString(sourceEntity)); + cosmosObjectNode = + (ObjectNode)objectMapper.readTree(objectMapper.writeValueAsString(sourceEntity)); } catch (JsonProcessingException e) { throw new CosmosDBAccessException("Failed to map document value.", e); } @@ -133,14 +126,15 @@ public CosmosItemProperties writeCosmosItemProperties(Object sourceEntity) { if (idProperty != null) { final Object value = accessor.getProperty(idProperty); final String id = value == null ? null : value.toString(); - cosmosItemProperties.id(id); + cosmosObjectNode.put("id", id); } - return cosmosItemProperties; + return cosmosObjectNode; } /** * To get application context + * * @return ApplicationContext */ public ApplicationContext getApplicationContext() { @@ -159,6 +153,7 @@ public ConversionService getConversionService() { /** * To get mapping context + * * @return MappingContext */ public MappingContext, CosmosPersistentProperty> getMappingContext() { @@ -171,7 +166,8 @@ private ConvertingPropertyAccessor getPropertyAccessor(Object entity) { mappingContext.getPersistentEntity(entity.getClass()); Assert.notNull(entityInformation, "EntityInformation should not be null."); - final PersistentPropertyAccessor accessor = entityInformation.getPropertyAccessor(entity); + final PersistentPropertyAccessor accessor = + entityInformation.getPropertyAccessor(entity); return new ConvertingPropertyAccessor<>(accessor, conversionService); } @@ -186,13 +182,14 @@ public static Object toCosmosDbValue(Object fromPropertyValue) { return null; } - // com.microsoft.azure.data.cosmos.JsonSerializable#set(String, T) cannot set values for Date and Enum correctly + // com.microsoft.azure.data.cosmos.JsonSerializable#set(String, T) cannot set values for + // Date and Enum correctly if (fromPropertyValue instanceof Date) { - fromPropertyValue = ((Date) fromPropertyValue).getTime(); + fromPropertyValue = ((Date)fromPropertyValue).getTime(); } else if (fromPropertyValue instanceof ZonedDateTime) { - fromPropertyValue = ((ZonedDateTime) fromPropertyValue) - .format(DateTimeFormatter.ofPattern(ISO_8601_COMPATIBLE_DATE_PATTERN)); + fromPropertyValue = ((ZonedDateTime)fromPropertyValue) + .format(DateTimeFormatter.ofPattern(ISO_8601_COMPATIBLE_DATE_PATTERN)); } else if (fromPropertyValue instanceof Enum) { fromPropertyValue = fromPropertyValue.toString(); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/AbstractQueryGenerator.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/AbstractQueryGenerator.java index 680ec4045ac5..b264ec7f62ba 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/AbstractQueryGenerator.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/AbstractQueryGenerator.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.generator; -import com.azure.data.cosmos.SqlParameterList; -import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.cosmos.models.SqlParameter; +import com.azure.cosmos.models.SqlQuerySpec; import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; import com.azure.spring.data.cosmos.core.query.DocumentQuery; @@ -208,19 +208,15 @@ private String generateQueryTail(@NonNull DocumentQuery query) { protected SqlQuerySpec generateCosmosQuery(@NonNull DocumentQuery query, - @NonNull String queryHead) { + @NonNull String queryHead) { final Pair>> queryBody = generateQueryBody(query); final String queryString = String.join(" ", queryHead, queryBody.getValue0(), generateQueryTail(query)); final List> parameters = queryBody.getValue1(); - final SqlParameterList sqlParameters = - new SqlParameterList(); - - sqlParameters.addAll( - parameters.stream() - .map(p -> new com.azure.data.cosmos.SqlParameter("@" - + p.getValue0(), toCosmosDbValue(p.getValue1()))) - .collect(Collectors.toList()) - ); + + List sqlParameters = parameters.stream() + .map(p -> new SqlParameter("@" + p.getValue0(), + toCosmosDbValue(p.getValue1()))) + .collect(Collectors.toList()); return new SqlQuerySpec(queryString, sqlParameters); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/CountQueryGenerator.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/CountQueryGenerator.java index c8f0d25d928f..20f87b5fecf5 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/CountQueryGenerator.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/CountQueryGenerator.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.generator; -import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.cosmos.models.SqlQuerySpec; import com.azure.spring.data.cosmos.core.query.DocumentQuery; /** diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/FindQuerySpecGenerator.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/FindQuerySpecGenerator.java index ff5e128bead1..fb0e53a75222 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/FindQuerySpecGenerator.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/FindQuerySpecGenerator.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.generator; -import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.cosmos.models.SqlQuerySpec; import com.azure.spring.data.cosmos.core.query.DocumentQuery; /** diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/QuerySpecGenerator.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/QuerySpecGenerator.java index d460d2e266b3..22f92b367d10 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/QuerySpecGenerator.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/generator/QuerySpecGenerator.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.generator; -import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.cosmos.models.SqlQuerySpec; import com.azure.spring.data.cosmos.core.query.DocumentQuery; /** diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/CosmosPersistentEntity.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/CosmosPersistentEntity.java index 189febbf8ce3..570a12ed79ee 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/CosmosPersistentEntity.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/CosmosPersistentEntity.java @@ -9,13 +9,6 @@ * Represents a cosmos persistent entity. */ public interface CosmosPersistentEntity extends PersistentEntity { - /** - * To get collection - * @return String - * @deprecated use {@link #getContainer()} instead - */ - @Deprecated - String getCollection(); /** * To get container of entity diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/Document.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/Document.java index 511cea4d7fa3..3df927d705a3 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/Document.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/Document.java @@ -5,11 +5,11 @@ import com.azure.spring.data.cosmos.Constants; import org.springframework.data.annotation.Persistent; +import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.lang.annotation.ElementType; /** * Annotation of cosmos document @@ -20,10 +20,10 @@ @Target({ElementType.TYPE}) public @interface Document { /** - * To set collection name + * To set container name * @return String */ - String collection() default Constants.DEFAULT_COLLECTION_NAME; + String container() default Constants.DEFAULT_CONTAINER_NAME; /** * To set request unit @@ -38,8 +38,8 @@ int timeToLive() default Constants.DEFAULT_TIME_TO_LIVE; /** - * To set if create collection automatically + * To set if create container automatically * @return default as true */ - boolean autoCreateCollection() default Constants.DEFAULT_AUTO_CREATE_CONTAINER; + boolean autoCreateContainer() default Constants.DEFAULT_AUTO_CREATE_CONTAINER; } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/DocumentIndexingPolicy.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/DocumentIndexingPolicy.java index 1e794e2d14e6..12f9386c16d0 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/DocumentIndexingPolicy.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/DocumentIndexingPolicy.java @@ -2,15 +2,15 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.mapping; -import com.azure.data.cosmos.IndexingMode; +import com.azure.cosmos.models.IndexingMode; import com.azure.spring.data.cosmos.Constants; import org.springframework.data.annotation.Persistent; +import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.lang.annotation.ElementType; /** * Annotation for document indexing policy @@ -24,7 +24,7 @@ * To set automatic indexing * @return default as true */ - boolean automatic() default Constants.DEFAULT_INDEXINGPOLICY_AUTOMATIC; + boolean automatic() default Constants.DEFAULT_INDEXING_POLICY_AUTOMATIC; /** * To set indexing mode diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/PartitionKey.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/PartitionKey.java index 680b06ec2471..937d70201aa5 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/PartitionKey.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/mapping/PartitionKey.java @@ -2,11 +2,11 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.mapping; +import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.lang.annotation.ElementType; /** * Interface for type partition key diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CosmosPageRequest.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CosmosPageRequest.java index 5f42092af3c3..7ae26c79f335 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CosmosPageRequest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CosmosPageRequest.java @@ -2,14 +2,16 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.query; -import com.azure.data.cosmos.FeedResponse; +import com.azure.cosmos.models.FeedResponse; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; +import java.util.Objects; + /** * CosmosPageRequest representing page request during pagination query, field - * {@link FeedResponse#continuationToken()} response continuation token} is saved + * {@link FeedResponse#getContinuationToken()} response continuation token} is saved * to help query next page. *

* The requestContinuation token should be saved after each request and reused in later queries. @@ -128,8 +130,7 @@ public boolean equals(Object obj) { final CosmosPageRequest that = (CosmosPageRequest) obj; - final boolean continuationTokenEquals = requestContinuation != null - ? requestContinuation.equals(that.requestContinuation) : that.requestContinuation == null; + final boolean continuationTokenEquals = Objects.equals(requestContinuation, that.requestContinuation); return continuationTokenEquals && super.equals(that); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CriteriaType.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CriteriaType.java index 153a76b94909..577be6de20c8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CriteriaType.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/query/CriteriaType.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.query; -import org.springframework.lang.NonNull; import org.springframework.data.repository.query.parser.Part; +import org.springframework.lang.NonNull; import java.beans.ConstructorProperties; import java.util.Collections; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBAccessException.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBAccessException.java index 0a0d29725f39..ab4de49617a2 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBAccessException.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBAccessException.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.exception; -import com.azure.data.cosmos.CosmosClientException; +import com.azure.cosmos.CosmosException; import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.repository.ReactiveCosmosRepository; import org.springframework.dao.DataAccessException; @@ -19,7 +19,7 @@ */ public class CosmosDBAccessException extends DataAccessException { - protected final CosmosClientException cosmosClientException; + protected final CosmosException cosmosException; /** * Construct a {@code CosmosDBAccessException} with the specified detail message. @@ -27,7 +27,7 @@ public class CosmosDBAccessException extends DataAccessException { */ public CosmosDBAccessException(String msg) { super(msg); - this.cosmosClientException = null; + this.cosmosException = null; } /** @@ -38,10 +38,10 @@ public CosmosDBAccessException(String msg) { */ public CosmosDBAccessException(@Nullable String msg, @Nullable Throwable cause) { super(msg, cause); - if (cause instanceof CosmosClientException) { - this.cosmosClientException = (CosmosClientException) cause; + if (cause instanceof CosmosException) { + this.cosmosException = (CosmosException) cause; } else { - this.cosmosClientException = null; + this.cosmosException = null; } } @@ -54,16 +54,16 @@ public CosmosDBAccessException(@Nullable String msg, @Nullable Throwable cause) */ public CosmosDBAccessException(@Nullable String msg, @Nullable Exception cause) { super(msg, cause); - this.cosmosClientException = cause instanceof CosmosClientException - ? (CosmosClientException) cause + this.cosmosException = cause instanceof CosmosException + ? (CosmosException) cause : null; } /** * To get exception object for cosmos client - * @return CosmosClientException + * @return CosmosException */ - public CosmosClientException getCosmosClientException() { - return cosmosClientException; + public CosmosException getCosmosException() { + return cosmosException; } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBExceptionUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBExceptionUtils.java index 84c1dfae68ca..6c285ed160b0 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBExceptionUtils.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBExceptionUtils.java @@ -2,14 +2,13 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.exception; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.cosmos.CosmosException; import org.springframework.util.StringUtils; import reactor.core.Exceptions; import reactor.core.publisher.Mono; /** - * To handle and throw a cosmosdb exception when access the database + * To handle and throw a cosmos db exception when access the database */ public class CosmosDBExceptionUtils { @@ -20,11 +19,11 @@ public class CosmosDBExceptionUtils { * @param throwable exception * @param type class of Mono * @return Mono instance - * @throws CosmosDBAccessException for operations on cosmosdb + * @throws CosmosDBAccessException for operations on cosmos db */ public static Mono exceptionHandler(String message, Throwable throwable) { if (StringUtils.isEmpty(message)) { - message = "Failed to access cosmosdb database"; + message = "Failed to access cosmos db database"; } // Unwrap the exception in case if it is a reactive exception final Throwable unwrappedThrowable = Exceptions.unwrap(throwable); @@ -32,7 +31,7 @@ public static Mono exceptionHandler(String message, Throwable throwable) } /** - * To find an exceptionHandler for a excetption and return empty Mono if the exception status code is not found + * To find an exceptionHandler for a exception and return empty Mono if the exception status code is not found * * @param message the detail message * @param throwable exception @@ -42,9 +41,9 @@ public static Mono exceptionHandler(String message, Throwable throwable) public static Mono findAPIExceptionHandler(String message, Throwable throwable) { // Unwrap the exception in case if it is a reactive exception final Throwable unwrappedThrowable = Exceptions.unwrap(throwable); - if (unwrappedThrowable instanceof CosmosClientException) { - final CosmosClientException cosmosClientException = (CosmosClientException) unwrappedThrowable; - if (cosmosClientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) { + if (unwrappedThrowable instanceof CosmosException) { + final CosmosException cosmosClientException = (CosmosException) unwrappedThrowable; + if (cosmosClientException.getStatusCode() == 404) { return Mono.empty(); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/DatabaseCreationException.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/DatabaseCreationException.java index 0e3968dc4770..6b42de838600 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/DatabaseCreationException.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/DatabaseCreationException.java @@ -6,7 +6,7 @@ import org.springframework.lang.Nullable; /** - * General exception for illegal creation of cosmosdb + * General exception for illegal creation of cosmos db */ public class DatabaseCreationException extends DataAccessException { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/IllegalCollectionException.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/IllegalCollectionException.java index 0344ff842f50..991338998643 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/IllegalCollectionException.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/IllegalCollectionException.java @@ -6,7 +6,7 @@ import org.springframework.lang.Nullable; /** - * General exception for illegal collection of cosmosdb + * General exception for illegal collection of cosmos db */ public class IllegalCollectionException extends DataAccessException { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/IllegalQueryException.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/IllegalQueryException.java index 59c95cb9c5af..e1027f879cc3 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/IllegalQueryException.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/IllegalQueryException.java @@ -6,7 +6,7 @@ import org.springframework.lang.Nullable; /** - * General exception for illegal query of cosmosdb + * General exception for illegal query of cosmos db */ public class IllegalQueryException extends DataAccessException { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/CosmosRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/CosmosRepository.java index 2591d8502cda..170604c72d5a 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/CosmosRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/CosmosRepository.java @@ -3,7 +3,7 @@ package com.azure.spring.data.cosmos.repository; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.PartitionKey; import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.PagingAndSortingRepository; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/ReactiveCosmosRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/ReactiveCosmosRepository.java index 4b35604e0f3a..60a28bec9397 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/ReactiveCosmosRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/ReactiveCosmosRepository.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.PartitionKey; import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.reactive.ReactiveSortingRepository; import reactor.core.publisher.Flux; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/CosmosRepositoryConfigurationExtension.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/CosmosRepositoryConfigurationExtension.java index 20466b923177..4ae480a3b25e 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/CosmosRepositoryConfigurationExtension.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/CosmosRepositoryConfigurationExtension.java @@ -3,10 +3,10 @@ package com.azure.spring.data.cosmos.repository.config; -import com.azure.spring.data.cosmos.repository.support.CosmosRepositoryFactoryBean; import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; import com.azure.spring.data.cosmos.repository.CosmosRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosRepositoryFactoryBean; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; @@ -27,12 +27,12 @@ public class CosmosRepositoryConfigurationExtension extends RepositoryConfigurat @Override public String getModuleName() { - return Constants.COSMOSDB_MODULE_NAME; + return Constants.COSMOS_MODULE_NAME; } @Override public String getModulePrefix() { - return Constants.COSMOSDB_MODULE_PREFIX; + return Constants.COSMOS_MODULE_PREFIX; } /** diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/EnableCosmosRepositories.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/EnableCosmosRepositories.java index 5ac564c4aac2..a2a0cc4b62f8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/EnableCosmosRepositories.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/EnableCosmosRepositories.java @@ -3,8 +3,8 @@ package com.azure.spring.data.cosmos.repository.config; -import com.azure.spring.data.cosmos.repository.support.CosmosRepositoryFactoryBean; import com.azure.spring.data.cosmos.Constants; +import com.azure.spring.data.cosmos.repository.support.CosmosRepositoryFactoryBean; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Import; import org.springframework.data.repository.config.DefaultRepositoryBaseClass; @@ -28,7 +28,7 @@ public @interface EnableCosmosRepositories { /** - * Toset repo value + * To set repo value * @return default as {} */ String[] value() default {}; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/EnableReactiveCosmosRepositories.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/EnableReactiveCosmosRepositories.java index c1c9d5aae91b..ade7e47fbed2 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/EnableReactiveCosmosRepositories.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/EnableReactiveCosmosRepositories.java @@ -3,8 +3,8 @@ package com.azure.spring.data.cosmos.repository.config; -import com.azure.spring.data.cosmos.repository.support.ReactiveCosmosRepositoryFactoryBean; import com.azure.spring.data.cosmos.Constants; +import com.azure.spring.data.cosmos.repository.support.ReactiveCosmosRepositoryFactoryBean; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Import; import org.springframework.data.repository.config.DefaultRepositoryBaseClass; @@ -28,7 +28,7 @@ public @interface EnableReactiveCosmosRepositories { /** - * Toset repo value + * To set repo value * @return default as {} */ String[] value() default {}; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/ReactiveCosmosRepositoryConfigurationExtension.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/ReactiveCosmosRepositoryConfigurationExtension.java index c195bc1339f9..c8541b2d9ff8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/ReactiveCosmosRepositoryConfigurationExtension.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/config/ReactiveCosmosRepositoryConfigurationExtension.java @@ -3,10 +3,10 @@ package com.azure.spring.data.cosmos.repository.config; -import com.azure.spring.data.cosmos.repository.support.ReactiveCosmosRepositoryFactoryBean; import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; import com.azure.spring.data.cosmos.repository.ReactiveCosmosRepository; +import com.azure.spring.data.cosmos.repository.support.ReactiveCosmosRepositoryFactoryBean; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; @@ -27,12 +27,12 @@ public class ReactiveCosmosRepositoryConfigurationExtension extends RepositoryCo @Override public String getModuleName() { - return Constants.COSMOSDB_MODULE_NAME; + return Constants.COSMOS_MODULE_NAME; } @Override public String getModulePrefix() { - return Constants.COSMOSDB_MODULE_PREFIX; + return Constants.COSMOS_MODULE_PREFIX; } /** diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/CosmosEntityMetadata.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/CosmosEntityMetadata.java index db59937c5738..204c69d55b3a 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/CosmosEntityMetadata.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/CosmosEntityMetadata.java @@ -9,14 +9,6 @@ */ public interface CosmosEntityMetadata extends EntityMetadata { - /** - * Get collection name from the given entity - * @return String - * @deprecated use {@link #getContainerName()} instead - */ - @Deprecated - String getCollectionName(); - /** * Get container name from the given entity * @return String diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/CosmosQueryCreator.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/CosmosQueryCreator.java index ceafd6096c32..06c4e33394d9 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/CosmosQueryCreator.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/CosmosQueryCreator.java @@ -2,12 +2,12 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.query; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentProperty; import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; import com.azure.spring.data.cosmos.core.query.DocumentQuery; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.springframework.data.domain.Sort; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.repository.query.parser.AbstractQueryCreator; @@ -20,7 +20,7 @@ import java.util.Iterator; import java.util.List; /** - * TODO: String based query, based on how cosmosdb provides. + * TODO: String based query, based on how cosmosDB provides. * StringCosmosQuery class, * How to bind values to the query. if CosmosDb already has binding capability, if not we would have to do it here in * some creative way.query creator are associated with part tree queries, diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/PartTreeCosmosQuery.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/PartTreeCosmosQuery.java index ad4d06a2c777..de43a7bbf557 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/PartTreeCosmosQuery.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/PartTreeCosmosQuery.java @@ -3,8 +3,8 @@ package com.azure.spring.data.cosmos.repository.query; import com.azure.spring.data.cosmos.core.CosmosOperations; -import com.azure.spring.data.cosmos.core.query.DocumentQuery; import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentProperty; +import com.azure.spring.data.cosmos.core.query.DocumentQuery; import org.apache.commons.lang3.NotImplementedException; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.repository.query.ResultProcessor; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/PartTreeReactiveCosmosQuery.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/PartTreeReactiveCosmosQuery.java index 0611a21b5cc7..71e29ed82583 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/PartTreeReactiveCosmosQuery.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/PartTreeReactiveCosmosQuery.java @@ -5,7 +5,6 @@ import com.azure.spring.data.cosmos.core.ReactiveCosmosOperations; import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentProperty; import com.azure.spring.data.cosmos.core.query.DocumentQuery; -import org.apache.commons.lang3.NotImplementedException; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.repository.query.ResultProcessor; import org.springframework.data.repository.query.parser.Part; @@ -41,7 +40,7 @@ protected DocumentQuery createQuery(ReactiveCosmosParameterAccessor accessor) { final DocumentQuery query = creator.createQuery(); if (tree.isLimiting()) { - throw new NotImplementedException("Limiting is not supported."); + throw new UnsupportedOperationException("Limiting is not supported."); } return query; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/ReactiveCosmosEntityMetadata.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/ReactiveCosmosEntityMetadata.java index d7adefad76fc..91e2505dd262 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/ReactiveCosmosEntityMetadata.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/ReactiveCosmosEntityMetadata.java @@ -9,14 +9,6 @@ */ public interface ReactiveCosmosEntityMetadata extends EntityMetadata { - /** - * Get collection name from the given entity - * @return String - * @deprecated use {@link #getContainerName()} instead - */ - @Deprecated - String getCollectionName(); - /** * Get container name from the given entity * @return String diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/ReactiveCosmosQueryCreator.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/ReactiveCosmosQueryCreator.java index 300651feefff..b3ce91a962be 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/ReactiveCosmosQueryCreator.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/query/ReactiveCosmosQueryCreator.java @@ -2,12 +2,12 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.query; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentProperty; import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; import com.azure.spring.data.cosmos.core.query.DocumentQuery; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.springframework.data.domain.Sort; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.repository.query.parser.AbstractQueryCreator; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/CosmosEntityInformation.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/CosmosEntityInformation.java index 268a2c6914d8..d7dfbb44ea8b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/CosmosEntityInformation.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/CosmosEntityInformation.java @@ -3,31 +3,29 @@ package com.azure.spring.data.cosmos.repository.support; -import com.azure.data.cosmos.ExcludedPath; -import com.azure.data.cosmos.IncludedPath; -import com.azure.data.cosmos.IndexingMode; -import com.azure.data.cosmos.IndexingPolicy; +import com.azure.cosmos.models.ExcludedPath; +import com.azure.cosmos.models.IncludedPath; +import com.azure.cosmos.models.IndexingMode; +import com.azure.cosmos.models.IndexingPolicy; import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; import org.apache.commons.lang3.reflect.FieldUtils; - -import org.json.JSONObject; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Version; import org.springframework.data.repository.core.support.AbstractEntityInformation; import org.springframework.lang.NonNull; import org.springframework.util.ReflectionUtils; -import static com.azure.spring.data.cosmos.common.ExpressionResolver.resolveExpression; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; +import static com.azure.spring.data.cosmos.common.ExpressionResolver.resolveExpression; + /** - * Class to describe cosmosdb entity + * Class to describe cosmosDb entity */ public class CosmosEntityInformation extends AbstractEntityInformation { @@ -39,7 +37,7 @@ public class CosmosEntityInformation extends AbstractEntityInformation getIdType() { return (Class) id.getType(); } - /** - * Get collection name - * - * @return collection name - * @deprecated Use {@link #getContainerName()} instead - */ - @Deprecated - public String getCollectionName() { - return this.containerName; - } - /** * Get container name * @@ -178,17 +165,6 @@ public String getPartitionKeyFieldValue(T entity) { return partitionKeyField == null ? null : (String) ReflectionUtils.getField(partitionKeyField, entity); } - /** - * Check if auto creating collection is allowed - * - * @return boolean - * @deprecated Use {@link #isAutoCreateContainer()} instead. - */ - @Deprecated - public boolean isAutoCreateCollection() { - return autoCreateContainer; - } - /** * Check if auto creating container is allowed * @@ -201,10 +177,10 @@ public boolean isAutoCreateContainer() { private IndexingPolicy getIndexingPolicy(Class domainType) { final IndexingPolicy policy = new IndexingPolicy(); - policy.automatic(this.getIndexingPolicyAutomatic(domainType)); - policy.indexingMode(this.getIndexingPolicyMode(domainType)); + policy.setAutomatic(this.getIndexingPolicyAutomatic(domainType)); + policy.setIndexingMode(this.getIndexingPolicyMode(domainType)); policy.setIncludedPaths(this.getIndexingPolicyIncludePaths(domainType)); - policy.excludedPaths(this.getIndexingPolicyExcludePaths(domainType)); + policy.setExcludedPaths(this.getIndexingPolicyExcludePaths(domainType)); return policy; } @@ -238,9 +214,9 @@ private String getContainerName(Class domainType) { final Document annotation = domainType.getAnnotation(Document.class); if (annotation != null - && annotation.collection() != null - && !annotation.collection().isEmpty()) { - customContainerName = resolveExpression(annotation.collection()); + && annotation.container() != null + && !annotation.container().isEmpty()) { + customContainerName = resolveExpression(annotation.container()); } return customContainerName; @@ -290,7 +266,7 @@ private Integer getTimeToLive(Class domainType) { private Boolean getIndexingPolicyAutomatic(Class domainType) { - Boolean isAutomatic = Boolean.valueOf(Constants.DEFAULT_INDEXINGPOLICY_AUTOMATIC); + Boolean isAutomatic = Boolean.valueOf(Constants.DEFAULT_INDEXING_POLICY_AUTOMATIC); final DocumentIndexingPolicy annotation = domainType.getAnnotation(DocumentIndexingPolicy.class); if (annotation != null) { @@ -301,7 +277,7 @@ private Boolean getIndexingPolicyAutomatic(Class domainType) { } private IndexingMode getIndexingPolicyMode(Class domainType) { - IndexingMode mode = Constants.DEFAULT_INDEXINGPOLICY_MODE; + IndexingMode mode = Constants.DEFAULT_INDEXING_POLICY_MODE; final DocumentIndexingPolicy annotation = domainType.getAnnotation(DocumentIndexingPolicy.class); if (annotation != null) { @@ -315,7 +291,7 @@ private List getIndexingPolicyIncludePaths(Class domainType) { final List pathArrayList = new ArrayList<>(); final DocumentIndexingPolicy annotation = domainType.getAnnotation(DocumentIndexingPolicy.class); - if (annotation == null || annotation.includePaths() == null || annotation.includePaths().length == 0) { + if (annotation == null || annotation.includePaths().length == 0) { return null; // Align the default value of IndexingPolicy } @@ -338,8 +314,7 @@ private List getIndexingPolicyExcludePaths(Class domainType) { final String[] rawPaths = annotation.excludePaths(); for (final String path : rawPaths) { - final JSONObject obj = new JSONObject(path); - pathArrayList.add(new ExcludedPath().path(obj.get("path").toString())); + pathArrayList.add(new ExcludedPath(path)); } return pathArrayList; @@ -357,7 +332,7 @@ private boolean getIsAutoCreateContainer(Class domainType) { boolean autoCreateContainer = Constants.DEFAULT_AUTO_CREATE_CONTAINER; if (annotation != null) { - autoCreateContainer = annotation.autoCreateCollection(); + autoCreateContainer = annotation.autoCreateContainer(); } return autoCreateContainer; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/CosmosRepositoryFactory.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/CosmosRepositoryFactory.java index 924aa773ed49..3eab5d73fc0c 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/CosmosRepositoryFactory.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/CosmosRepositoryFactory.java @@ -33,7 +33,7 @@ public class CosmosRepositoryFactory extends RepositoryFactorySupport { /** * Initialization * - * @param cosmosOperations for cosmosdb operations + * @param cosmosOperations for cosmosDb operations * @param applicationContext for the context */ public CosmosRepositoryFactory(CosmosOperations cosmosOperations, ApplicationContext applicationContext) { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/ReactiveCosmosRepositoryFactory.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/ReactiveCosmosRepositoryFactory.java index 6b13c5f98c00..f8433d989417 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/ReactiveCosmosRepositoryFactory.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/ReactiveCosmosRepositoryFactory.java @@ -32,7 +32,7 @@ public class ReactiveCosmosRepositoryFactory extends ReactiveRepositoryFactorySu /** * Initialization * - * @param cosmosOperations for cosmosdb operations + * @param cosmosOperations for cosmosDB operations * @param applicationContext for the context */ public ReactiveCosmosRepositoryFactory(ReactiveCosmosOperations cosmosOperations, diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/ReactiveCosmosRepositoryFactoryBean.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/ReactiveCosmosRepositoryFactoryBean.java index 20b191d066f2..de81d5415b91 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/ReactiveCosmosRepositoryFactoryBean.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/ReactiveCosmosRepositoryFactoryBean.java @@ -39,7 +39,7 @@ public ReactiveCosmosRepositoryFactoryBean(Class repositoryInterfac } /** - * Set reactive Cosmosdb operations + * Set reactive CosmosDB operations * * @param operations contains cosmos operations */ diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleCosmosRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleCosmosRepository.java index ecf21da9d110..f82a702575b6 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleCosmosRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleCosmosRepository.java @@ -3,8 +3,8 @@ package com.azure.spring.data.cosmos.repository.support; -import com.azure.data.cosmos.CosmosContainerProperties; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.core.CosmosOperations; import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; @@ -35,7 +35,7 @@ public class SimpleCosmosRepository implements Cosmo /** * Initialization * - * @param metadata for cosmos entity information + * @param metadata for cosmos entity information * @param applicationContext to get bean of CosmosOperations class */ public SimpleCosmosRepository(CosmosEntityInformation metadata, @@ -51,8 +51,8 @@ public SimpleCosmosRepository(CosmosEntityInformation metadata, /** * Initialization * - * @param metadata for cosmos entity information - * @param dbOperations for cosmosdb operation + * @param metadata for cosmos entity information + * @param dbOperations for cosmosDB operation */ public SimpleCosmosRepository(CosmosEntityInformation metadata, CosmosOperations dbOperations) { @@ -72,7 +72,7 @@ private CosmosContainerProperties createContainerIfNotExists() { * save entity without partition * * @param entity to be saved - * @param type of entity + * @param type of entity * @return entity */ @Override @@ -82,17 +82,16 @@ public S save(S entity) { // save entity if (information.isNew(entity)) { return operation.insert(information.getContainerName(), - entity, - createKey(information.getPartitionKeyFieldValue(entity))); + entity, + createKey(information.getPartitionKeyFieldValue(entity))); } else { - return operation.upsertAndReturnEntity(information.getContainerName(), - entity, createKey(information.getPartitionKeyFieldValue(entity))); + return operation.upsertAndReturnEntity(information.getContainerName(), entity); } } private PartitionKey createKey(String partitionKeyValue) { if (StringUtils.isEmpty(partitionKeyValue)) { - return PartitionKey.None; + return PartitionKey.NONE; } return new PartitionKey(partitionKeyValue); @@ -102,7 +101,7 @@ private PartitionKey createKey(String partitionKeyValue) { * batch save entities * * @param entities Batch entities - * @param type of entities + * @param type of entities * @return return the saved entities */ @Override @@ -152,11 +151,12 @@ public Optional findById(ID id) { Assert.notNull(id, "id must not be null"); if (id instanceof String - && !StringUtils.hasText((String) id)) { + && !StringUtils.hasText((String)id)) { return Optional.empty(); } - return Optional.ofNullable(operation.findById(information.getContainerName(), id, information.getJavaType())); + return Optional.ofNullable(operation.findById(information.getContainerName(), id, + information.getJavaType())); } @Override @@ -164,7 +164,7 @@ public Optional findById(ID id, PartitionKey partitionKey) { Assert.notNull(id, "id must not be null"); if (id instanceof String - && !StringUtils.hasText((String) id)) { + && !StringUtils.hasText((String)id)) { return Optional.empty(); } @@ -213,8 +213,8 @@ public void delete(T entity) { final String partitionKeyValue = information.getPartitionKeyFieldValue(entity); operation.deleteById(information.getContainerName(), - information.getId(entity), - partitionKeyValue == null ? null : new PartitionKey(partitionKeyValue)); + information.getId(entity), + partitionKeyValue == null ? null : new PartitionKey(partitionKeyValue)); } /** @@ -259,7 +259,8 @@ public boolean existsById(ID primaryKey) { @Override public Iterable findAll(@NonNull Sort sort) { Assert.notNull(sort, "sort of findAll should not be null"); - final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)).with(sort); + final DocumentQuery query = + new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)).with(sort); return operation.find(query, information.getJavaType(), information.getContainerName()); } @@ -275,7 +276,8 @@ public Iterable findAll(@NonNull Sort sort) { public Page findAll(Pageable pageable) { Assert.notNull(pageable, "pageable should not be null"); - return operation.findAll(pageable, information.getJavaType(), information.getContainerName()); + return operation.findAll(pageable, information.getJavaType(), + information.getContainerName()); } @Override diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleReactiveCosmosRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleReactiveCosmosRepository.java index 27bfe9652107..4359c52c5e52 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleReactiveCosmosRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleReactiveCosmosRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.support; -import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.CosmosContainerResponse; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.core.ReactiveCosmosOperations; import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; @@ -90,8 +90,7 @@ public Mono save(S entity) { entity, createKey(entityInformation.getPartitionKeyFieldValue(entity))); } else { - return cosmosOperations.upsert(entityInformation.getContainerName(), - entity, createKey(entityInformation.getPartitionKeyFieldValue(entity))); + return cosmosOperations.upsert(entityInformation.getContainerName(), entity); } } @@ -228,8 +227,7 @@ public Mono deleteAll(Publisher entityStream) { @Override public Mono deleteAll() { - return cosmosOperations.deleteAll(entityInformation.getContainerName(), - entityInformation.getPartitionKeyFieldName()); + return cosmosOperations.deleteAll(entityInformation.getContainerName(), entityInformation.getJavaType()); } private PartitionKey createKey(String partitionKeyValue) { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java index 9fbdeefe2564..720e707d0004 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java @@ -6,17 +6,18 @@ * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING * LINE NUMBERS OF EXISTING CODE SAMPLES. */ -import com.azure.data.cosmos.CosmosKeyCredential; + +import com.azure.core.credential.AzureKeyCredential; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.core.ResponseDiagnostics; import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; import io.micrometer.core.lang.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; @Configuration @EnableCosmosRepositories @@ -36,22 +37,24 @@ public class AppConfiguration extends AbstractCosmosConfiguration { @Value("${azure.cosmosdb.database}") private String dbName; - @Value("${azure.cosmosdb.populateQueryMetrics}") - private boolean populateQueryMetrics; + @Value("${azure.cosmosdb.queryMetricsEnabled}") + private boolean queryMetricsEnabled; - private CosmosKeyCredential cosmosKeyCredential; + private AzureKeyCredential azureKeyCredential; public CosmosDBConfig getConfig() { - this.cosmosKeyCredential = new CosmosKeyCredential(key); - CosmosDBConfig cosmosdbConfig = CosmosDBConfig.builder(uri, - this.cosmosKeyCredential, dbName).build(); - cosmosdbConfig.setPopulateQueryMetrics(populateQueryMetrics); - cosmosdbConfig.setResponseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()); - return cosmosdbConfig; + this.azureKeyCredential = new AzureKeyCredential(key); + CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder().endpoint(uri).credential(azureKeyCredential); + return CosmosDBConfig.builder() + .database(dbName) + .enableQueryMetrics(queryMetricsEnabled) + .cosmosClientBuilder(cosmosClientBuilder) + .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) + .build(); } public void switchToSecondaryKey() { - this.cosmosKeyCredential.key(secondaryKey); + this.azureKeyCredential.update(secondaryKey); } private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java index d44af1707fad..155e5852586c 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java @@ -8,8 +8,7 @@ * LINE NUMBERS OF EXISTING CODE SAMPLES. */ -import com.azure.data.cosmos.ConnectionMode; -import com.azure.data.cosmos.CosmosKeyCredential; +import com.azure.core.credential.AzureKeyCredential; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories; @@ -32,16 +31,15 @@ public class AppConfigurationCodeSnippet extends AbstractCosmosConfiguration { @Value("${azure.cosmosdb.database}") private String dbName; - @Value("${azure.cosmosdb.populateQueryMetrics}") - private boolean populateQueryMetrics; - - private CosmosKeyCredential cosmosKeyCredential; + @Value("${azure.cosmosdb.queryMetricsEnabled}") + private boolean queryMetricsEnabled; public CosmosDBConfig getConfig() { - this.cosmosKeyCredential = new CosmosKeyCredential(key); - CosmosDBConfig cosmosDbConfig = CosmosDBConfig.builder(uri, this.cosmosKeyCredential, dbName).build(); - cosmosDbConfig.getConnectionPolicy().connectionMode(ConnectionMode.DIRECT); - cosmosDbConfig.getConnectionPolicy().maxPoolSize(1000); - return cosmosDbConfig; + AzureKeyCredential azureKeyCredential = new AzureKeyCredential(key); + return CosmosDBConfig.builder() + .database(dbName) + .cosmosClientBuilder(new CosmosClientBuilder().credential(azureKeyCredential)) + .enableQueryMetrics(queryMetricsEnabled) + .build(); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDbProperties.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDBProperties.java similarity index 80% rename from sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDbProperties.java rename to sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDBProperties.java index 345d13361811..de52ce407c71 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDbProperties.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDBProperties.java @@ -10,7 +10,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "azure.cosmosdb") -public class CosmosDbProperties { +public class CosmosDBProperties { private String uri; @@ -20,7 +20,7 @@ public class CosmosDbProperties { private String database; - private boolean populateQueryMetrics; + private boolean queryMetricsEnabled; public String getUri() { return uri; @@ -54,11 +54,11 @@ public void setDatabase(String database) { this.database = database; } - public boolean isPopulateQueryMetrics() { - return populateQueryMetrics; + public boolean isQueryMetricsEnabled() { + return queryMetricsEnabled; } - public void setPopulateQueryMetrics(boolean populateQueryMetrics) { - this.populateQueryMetrics = populateQueryMetrics; + public void setQueryMetricsEnabled(boolean enableQueryMetrics) { + this.queryMetricsEnabled = enableQueryMetrics; } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/DocumentIndexingPolicyCodeSnippet.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/DocumentIndexingPolicyCodeSnippet.java index b68bf0f2b366..0b28a7cad7fe 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/DocumentIndexingPolicyCodeSnippet.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/DocumentIndexingPolicyCodeSnippet.java @@ -8,13 +8,13 @@ * LINE NUMBERS OF EXISTING CODE SAMPLES. */ -import com.azure.data.cosmos.IndexingMode; +import com.azure.cosmos.models.IndexingMode; import com.azure.spring.data.cosmos.Constants; public @interface DocumentIndexingPolicyCodeSnippet { // Indicate if indexing policy use automatic or not - boolean automatic() default Constants.DEFAULT_INDEXINGPOLICY_AUTOMATIC; + boolean automatic() default Constants.DEFAULT_INDEXING_POLICY_AUTOMATIC; // Indexing policy mode, option Consistent|Lazy|None. IndexingMode mode() default IndexingMode.CONSISTENT; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/MyDocument.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/MyDocument.java index 368b4f850b11..0251436588c2 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/MyDocument.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/MyDocument.java @@ -11,7 +11,7 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import org.springframework.data.annotation.Version; -@Document(collection = "myCollection") +@Document(container = "myContainer") public class MyDocument { String id; String data; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/User.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/User.java index 90a02d32c807..76e22408a7cd 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/User.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/User.java @@ -11,7 +11,7 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; -@Document(collection = "myCollection", ru = "400") +@Document(container = "myCollection", ru = "400") public class User { private String id; private String firstName; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java index f9d5c2a0baff..96de45a0acb7 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java @@ -6,7 +6,7 @@ * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING * LINE NUMBERS OF EXISTING CODE SAMPLES. */ -import com.azure.data.cosmos.CosmosKeyCredential; +import com.azure.core.credential.AzureKeyCredential; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.core.ResponseDiagnostics; @@ -19,42 +19,41 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; - -import javax.annotation.Nullable; - +import org.springframework.lang.Nullable; @Configuration -@EnableConfigurationProperties(CosmosDbProperties.class) +@EnableConfigurationProperties(CosmosDBProperties.class) @EnableReactiveCosmosRepositories @PropertySource("classpath:application.properties") public class UserRepositoryConfiguration extends AbstractCosmosConfiguration { private static final Logger logger = LoggerFactory.getLogger(AppConfiguration.class); @Autowired - private CosmosDbProperties properties; + private CosmosDBProperties properties; - private CosmosKeyCredential cosmosKeyCredential; + private AzureKeyCredential azureKeyCredential; @Bean public CosmosDBConfig cosmosDbConfig() { - this.cosmosKeyCredential = new CosmosKeyCredential(properties.getKey()); - CosmosDBConfig cosmosDBConfig = CosmosDBConfig.builder(properties.getUri(), cosmosKeyCredential, - properties.getDatabase()).build(); - cosmosDBConfig.setPopulateQueryMetrics(properties.isPopulateQueryMetrics()); - cosmosDBConfig.setResponseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()); - return cosmosDBConfig; + this.azureKeyCredential = new AzureKeyCredential(properties.getKey()); + return CosmosDBConfig.builder() + .database(properties.getDatabase()) + .cosmosClientBuilder(new CosmosClientBuilder().credential(azureKeyCredential)) + .enableQueryMetrics(properties.isQueryMetricsEnabled()) + .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) + .build(); } public void switchToSecondaryKey() { - this.cosmosKeyCredential.key(properties.getSecondaryKey()); + this.azureKeyCredential.update(properties.getSecondaryKey()); } public void switchToPrimaryKey() { - this.cosmosKeyCredential.key(properties.getKey()); + this.azureKeyCredential.update(properties.getKey()); } public void switchKey(String key) { - this.cosmosKeyCredential.key(key); + this.azureKeyCredential.update(key); } private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserSample.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserSample.java index cdf690cd992e..97468f2314d6 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserSample.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserSample.java @@ -11,7 +11,7 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import org.springframework.data.annotation.Id; -@Document(collection = "mycollection") +@Document(container = "mycollection") public class UserSample { @Id private String emailAddress; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDBFactoryTestIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDBFactoryTestIT.java new file mode 100644 index 000000000000..bcc9100d269a --- /dev/null +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDBFactoryTestIT.java @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.spring.data.cosmos; + +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.spring.data.cosmos.common.TestConstants; +import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.lang.reflect.Field; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TestRepositoryConfig.class) +public class CosmosDBFactoryTestIT { + + @Value("${cosmosdb.uri:}") + private String cosmosDbUri; + + @Value("${cosmosdb.key:}") + private String cosmosDbKey; + + @Test(expected = IllegalArgumentException.class) + public void testEmptyKey() { + final CosmosDBConfig dbConfig = CosmosDBConfig.builder() + .database(TestConstants.DB_NAME) + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(TestConstants.COSMOSDB_FAKE_HOST) + .key("")) + .build(); + new CosmosDBFactory(dbConfig).getCosmosSyncClient(); + } + + @Test + public void testInvalidEndpoint() { + final CosmosDBConfig dbConfig = CosmosDBConfig.builder() + .database(TestConstants.DB_NAME) + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(TestConstants.COSMOSDB_FAKE_HOST) + .key(TestConstants.COSMOSDB_FAKE_KEY)) + .build(); + final CosmosDBFactory factory = new CosmosDBFactory(dbConfig); + + assertThat(factory).isNotNull(); + } + + @Test + public void testConnectionPolicyUserAgentKept() throws IllegalAccessException { + final CosmosDBConfig dbConfig = CosmosDBConfig.builder() + .database(TestConstants.DB_NAME) + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(cosmosDbUri) + .key(cosmosDbKey)) + .build(); + + new CosmosDBFactory(dbConfig).getCosmosAsyncClient(); + + final String uaSuffix = getUserAgentSuffixValue(dbConfig.getCosmosClientBuilder()); + assertThat(uaSuffix).contains("spring-data"); + } + + private String getUserAgentSuffixValue(CosmosClientBuilder cosmosClientBuilder) throws IllegalAccessException { + final Field userAgentSuffix = FieldUtils.getDeclaredField(CosmosClientBuilder.class, + "userAgentSuffix", true); + return (String)userAgentSuffix.get(cosmosClientBuilder); + } +} diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDbFactoryTestIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDbFactoryTestIT.java deleted file mode 100644 index b1f853dbe403..000000000000 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDbFactoryTestIT.java +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.spring.data.cosmos; - -import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; -import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = TestRepositoryConfig.class) -public class CosmosDbFactoryTestIT { - - @Value("${cosmosdb.uri:}") - private String cosmosDbUri; - - @Value("${cosmosdb.key:}") - private String cosmosDbKey; - - @Test(expected = IllegalArgumentException.class) - public void testEmptyKey() { - final CosmosDBConfig dbConfig = CosmosDBConfig.builder(TestConstants.COSMOSDB_FAKE_HOST, - "", TestConstants.DB_NAME).build(); - new CosmosDbFactory(dbConfig); - } - - @Test - public void testInvalidEndpoint() { - final CosmosDBConfig dbConfig = - CosmosDBConfig.builder(TestConstants.COSMOSDB_FAKE_HOST, TestConstants.COSMOSDB_FAKE_KEY, TestConstants.DB_NAME).build(); - final CosmosDbFactory factory = new CosmosDbFactory(dbConfig); - - assertThat(factory).isNotNull(); - } - - @Test - public void testConnectWithConnectionString() { - final CosmosDBConfig dbConfig = - CosmosDBConfig.builder(TestConstants.COSMOSDB_FAKE_CONNECTION_STRING, TestConstants.DB_NAME).build(); - final CosmosDbFactory factory = new CosmosDbFactory(dbConfig); - - assertThat(factory).isNotNull(); - } - - @Test(expected = CosmosDBAccessException.class) - public void testInvalidConnectionString() { - CosmosDBConfig.builder(TestConstants.COSMOSDB_INVALID_FAKE_CONNECTION_STRING, TestConstants.DB_NAME).build(); - } - - @Test - public void testConnectionPolicyUserAgentKept() { - final CosmosDBConfig dbConfig = - CosmosDBConfig.builder(cosmosDbUri, cosmosDbKey, TestConstants.DB_NAME).build(); - final CosmosDbFactory factory = new CosmosDbFactory(dbConfig); - factory.getCosmosClient(); - - final String uaSuffix = factory.getConfig().getConnectionPolicy().userAgentSuffix(); - assertThat(uaSuffix).contains("spring-data"); - } -} diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/UserAgentTestIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/UserAgentTestIT.java deleted file mode 100644 index ba64a333b303..000000000000 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/UserAgentTestIT.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.spring.data.cosmos; - -import com.azure.spring.data.cosmos.common.PropertyLoader; -import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; -import org.assertj.core.api.Assertions; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.context.annotation.PropertySource; - -@Ignore("Cannot use fake uri and key with CosmosDbFactory as it tries the connection on new creation." - + "At the same time, cannot use mockito with real values, because it won't prepare PropertyLoader class for mocking") -@RunWith(PowerMockRunner.class) -@PrepareForTest(PropertyLoader.class) -@PropertySource(value = {"classpath:application.properties"}) -public class UserAgentTestIT { - - private static final String TEST_VERSION = "1.0.0-FOR-TEST"; - - @Test - public void testUserAgentSuffixAppended() { - PowerMockito.mockStatic(PropertyLoader.class); - Mockito.doReturn(TEST_VERSION).when(PropertyLoader.getProjectVersion()); - final CosmosDBConfig dbConfig = CosmosDBConfig.builder(TestConstants.COSMOSDB_FAKE_HOST, - TestConstants.COSMOSDB_FAKE_KEY, TestConstants.DB_NAME).build(); - final CosmosDbFactory factory = new CosmosDbFactory(dbConfig); - factory.getCosmosClient(); - Assertions.assertThat(factory.getConfig().getConnectionPolicy().userAgentSuffix()).contains(TEST_VERSION); - } - -} diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/DynamicContainer.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/DynamicContainer.java index 40eb9e50e07f..f7e486aa23b9 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/DynamicContainer.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/DynamicContainer.java @@ -4,7 +4,7 @@ package com.azure.spring.data.cosmos.common; public class DynamicContainer { - private String containerName; + private final String containerName; public DynamicContainer(String containerName) { this.containerName = containerName; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/ExpressionResolverUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/ExpressionResolverUnitTest.java index 652657597662..40bf96bfa513 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/ExpressionResolverUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/ExpressionResolverUnitTest.java @@ -12,11 +12,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -/** - * - * @author Domenico Sibilio - * - */ public class ExpressionResolverUnitTest { private static final String LITERAL_EXPRESSION = "literal expression"; private static final String SPEL_EXPRESSION = "#{@environment.getProperty('dynamic.collection.name')}"; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/MemoizerUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/MemoizerUnitTest.java index e29aeed50175..21000da50a2b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/MemoizerUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/MemoizerUnitTest.java @@ -13,11 +13,6 @@ import static org.junit.Assert.assertEquals; -/** - * - * @author Domenico Sibilio - * - */ public class MemoizerUnitTest { private static final String KEY = "key_1"; private static final Map countMap = new HashMap<>(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/ResponseDiagnosticsTestUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/ResponseDiagnosticsTestUtils.java index af5f731364b2..03d12c2048ee 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/ResponseDiagnosticsTestUtils.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/ResponseDiagnosticsTestUtils.java @@ -3,8 +3,7 @@ package com.azure.spring.data.cosmos.common; -import com.azure.data.cosmos.CosmosResponseDiagnostics; -import com.azure.data.cosmos.FeedResponseDiagnostics; +import com.azure.cosmos.CosmosDiagnostics; import com.azure.spring.data.cosmos.core.ResponseDiagnostics; import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; @@ -20,12 +19,8 @@ public ResponseDiagnosticsTestUtils() { }; } - public CosmosResponseDiagnostics getCosmosResponseDiagnostics() { - return diagnostics == null ? null : diagnostics.getCosmosResponseDiagnostics(); - } - - public FeedResponseDiagnostics getFeedResponseDiagnostics() { - return diagnostics == null ? null : diagnostics.getFeedResponseDiagnostics(); + public CosmosDiagnostics getCosmosDiagnostics() { + return diagnostics == null ? null : diagnostics.getCosmosDiagnostics(); } public ResponseDiagnostics.CosmosResponseStatistics getCosmosResponseStatistics() { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/TestConstants.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/TestConstants.java index f05aef2174c1..3bcfbecfa638 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/TestConstants.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/common/TestConstants.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.common; -import com.azure.data.cosmos.IndexingMode; +import com.azure.cosmos.models.IndexingMode; import com.azure.spring.data.cosmos.domain.Address; import java.util.Arrays; @@ -18,11 +18,10 @@ public final class TestConstants { public static final List

ADDRESSES = Arrays.asList(ADDRESS_1, ADDRESS_2); public static final int DEFAULT_TIME_TO_LIVE = -1; - public static final String DEFAULT_COLLECTION_NAME = "Person"; - public static final boolean DEFAULT_INDEXINGPOLICY_AUTOMATIC = true; - public static final IndexingMode DEFAULT_INDEXINGPOLICY_MODE = IndexingMode.CONSISTENT; - public static final String[] DEFAULT_EXCLUDEDPATHS = {}; - public static final String[] DEFAULT_INCLUDEDPATHS = { + public static final boolean DEFAULT_INDEXING_POLICY_AUTOMATIC = true; + public static final IndexingMode DEFAULT_INDEXING_POLICY_MODE = IndexingMode.CONSISTENT; + public static final String[] DEFAULT_EXCLUDED_PATHS = {}; + public static final String[] DEFAULT_INCLUDED_PATHS = { "{\"path\":\"/*\",\"indexes\":[" + "{\"kind\":\"Range\",\"dataType\":\"Number\",\"precision\":-1}," + "{\"kind\":\"Hash\",\"dataType\":\"String\",\"precision\":3}" @@ -31,47 +30,47 @@ public final class TestConstants { public static final String ROLE_COLLECTION_NAME = "RoleCollectionName"; public static final int TIME_TO_LIVE = 5; - public static final boolean INDEXINGPOLICY_AUTOMATIC = false; - public static final IndexingMode INDEXINGPOLICY_MODE = IndexingMode.LAZY; - public static final String INCLUDEDPATH_0 = "{\"path\":\"/*\",\"indexes\":[" + public static final boolean INDEXING_POLICY_AUTOMATIC = false; + public static final IndexingMode INDEXING_POLICY_MODE = IndexingMode.CONSISTENT; + public static final String INCLUDED_PATH_0 = "{\"path\":\"/*\",\"indexes\":[" + "{\"kind\":\"Range\",\"dataType\":\"Number\",\"precision\":2}," + "{\"kind\":\"Hash\",\"dataType\":\"String\",\"precision\":2}," + "{\"kind\":\"Spatial\",\"dataType\":\"Point\"}" + "]}"; - public static final String INCLUDEDPATH_1 = "{\"path\":\"/cache/*\",\"indexes\":[" + public static final String INCLUDED_PATH_1 = "{\"path\":\"/cache/*\",\"indexes\":[" + "{\"kind\":\"Range\",\"dataType\":\"Number\",\"precision\":3}," + "{\"kind\":\"Hash\",\"dataType\":\"String\",\"precision\":3}," + "{\"kind\":\"Spatial\",\"dataType\":\"LineString\"}" + "]}"; - public static final String INCLUDEDPATH_2 = "{\"path\":\"/entities/*\",\"indexes\":[" + public static final String INCLUDED_PATH_2 = "{\"path\":\"/entities/*\",\"indexes\":[" + "{\"kind\":\"Range\",\"dataType\":\"Number\",\"precision\":4}," + "{\"kind\":\"Hash\",\"dataType\":\"String\",\"precision\":4}," + "{\"kind\":\"Spatial\",\"dataType\":\"Polygon\"}" + "]}"; - public static final String[] INCLUDEDPATHS = { - INCLUDEDPATH_0, - INCLUDEDPATH_1, - INCLUDEDPATH_2, + public static final String[] INCLUDED_PATHS = { + INCLUDED_PATH_0, + INCLUDED_PATH_1, + INCLUDED_PATH_2, }; - public static final String EXCLUDEDPATH_0 = "{\"path\":\"/excluded/*\"}"; - public static final String EXCLUDEDPATH_1 = "{\"path\":\"/props/*\"}"; - public static final String[] EXCLUDEDPATHS = { - EXCLUDEDPATH_0, - EXCLUDEDPATH_1, + public static final String EXCLUDED_PATH_0 = "{\"path\":\"/excluded/*\"}"; + public static final String EXCLUDED_PATH_1 = "{\"path\":\"/props/*\"}"; + public static final String[] EXCLUDED_PATHS = { + EXCLUDED_PATH_0, + EXCLUDED_PATH_1, }; public static final String ORDER_BY_STRING_PATH = "{\"path\":\"/*\",\"indexes\":[" + "{\"kind\":\"Range\",\"dataType\":\"String\",\"precision\":-1}," + "]}"; - public static final String STARTSWITH_INCLUDEDPATH = + public static final String STARTS_WITH_INCLUDED_PATH = "{\"path\":\"/*\",\"indexes\":[" + "{\"kind\":\"Range\",\"dataType\":\"Number\",\"precision\":-1}," + "{\"kind\":\"Range\",\"dataType\":\"String\",\"precision\":3}" + "]}"; - public static final String[] PERSON_INCLUDEDPATHS = { - STARTSWITH_INCLUDEDPATH + public static final String[] PERSON_INCLUDED_PATHS = { + STARTS_WITH_INCLUDED_PATH }; public static final String DB_NAME = "testdb"; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfigurationIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfigurationIT.java index 734a73707973..b4fac37b0ba8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfigurationIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfigurationIT.java @@ -3,14 +3,15 @@ package com.azure.spring.data.cosmos.config; -import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.cosmos.ConsistencyLevel; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosClientBuilder; import com.azure.spring.data.cosmos.Constants; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.spring.data.cosmos.CosmosDBFactory; import com.azure.spring.data.cosmos.common.ExpressionResolver; -import com.fasterxml.jackson.databind.ObjectMapper; import com.azure.spring.data.cosmos.common.TestConstants; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.reflect.FieldUtils; import org.assertj.core.api.Assertions; import org.junit.Rule; import org.junit.Test; @@ -25,10 +26,11 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.util.StringUtils; +import java.lang.reflect.Field; + import static org.junit.Assert.assertNotNull; public class AbstractCosmosConfigurationIT { - private static final String OBJECTMAPPER_BEAN_NAME = Constants.OBJECTMAPPER_BEAN_NAME; @Rule public ExpectedException exception = ExpectedException.none(); @@ -46,7 +48,7 @@ public void containsCosmosDbFactory() { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( TestCosmosConfiguration.class); - Assertions.assertThat(context.getBean(CosmosDbFactory.class)).isNotNull(); + Assertions.assertThat(context.getBean(CosmosDBFactory.class)).isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) @@ -63,22 +65,25 @@ public void objectMapperIsConfigurable() { ObjectMapperConfiguration.class); Assertions.assertThat(context.getBean(ObjectMapper.class)).isNotNull(); - Assertions.assertThat(context.getBean(OBJECTMAPPER_BEAN_NAME)).isNotNull(); + Assertions.assertThat(context.getBean(Constants.OBJECT_MAPPER_BEAN_NAME)).isNotNull(); } @Test - public void testRequestOptionsConfigurable() { + public void testCosmosClientBuilderConfigurable() throws IllegalAccessException { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( RequestOptionsConfiguration.class); - final CosmosDbFactory factory = context.getBean(CosmosDbFactory.class); + final CosmosDBFactory factory = context.getBean(CosmosDBFactory.class); Assertions.assertThat(factory).isNotNull(); - final RequestOptions options = factory.getConfig().getRequestOptions(); + final CosmosClientBuilder cosmosClientBuilder = factory.getConfig().getCosmosClientBuilder(); - Assertions.assertThat(options).isNotNull(); - Assertions.assertThat(options.getConsistencyLevel()).isEqualTo(ConsistencyLevel.CONSISTENT_PREFIX); - Assertions.assertThat(options.isScriptLoggingEnabled()).isTrue(); + Assertions.assertThat(cosmosClientBuilder).isNotNull(); + final Field consistencyLevelField = FieldUtils.getDeclaredField(CosmosClientBuilder.class, + "desiredConsistencyLevel", true); + ConsistencyLevel consistencyLevel = + (ConsistencyLevel)consistencyLevelField.get(cosmosClientBuilder); + Assertions.assertThat(consistencyLevel).isEqualTo(ConsistencyLevel.CONSISTENT_PREFIX); } @Configuration @@ -95,23 +100,28 @@ static class TestCosmosConfiguration extends AbstractCosmosConfiguration { private String database; @Mock - private CosmosClient mockClient; + private CosmosAsyncClient mockClient; @Bean public CosmosDBConfig getConfig() { final String dbName = StringUtils.hasText(this.database) ? this.database : TestConstants.DB_NAME; - return CosmosDBConfig.builder(cosmosDbUri, cosmosDbKey, dbName).build(); + return CosmosDBConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(cosmosDbUri) + .key(cosmosDbKey)) + .database(dbName) + .build(); } @Override - public CosmosClient cosmosClient(CosmosDBConfig config) { + public CosmosAsyncClient cosmosAsyncClient(CosmosDBFactory cosmosDBFactory) { return mockClient; } } @Configuration static class ObjectMapperConfiguration extends TestCosmosConfiguration { - @Bean(name = OBJECTMAPPER_BEAN_NAME) + @Bean(name = Constants.OBJECT_MAPPER_BEAN_NAME) public ObjectMapper objectMapper() { return new ObjectMapper(); } @@ -130,22 +140,17 @@ static class RequestOptionsConfiguration extends AbstractCosmosConfiguration { @Value("${cosmosdb.database:}") private String database; - private RequestOptions getRequestOptions() { - final RequestOptions options = new RequestOptions(); - - options.setConsistencyLevel(ConsistencyLevel.CONSISTENT_PREFIX); - options.setScriptLoggingEnabled(true); - - return options; - } - @Bean public CosmosDBConfig getConfig() { final String dbName = StringUtils.hasText(this.database) ? this.database : TestConstants.DB_NAME; - final RequestOptions options = getRequestOptions(); - return CosmosDBConfig.builder(cosmosDbUri, cosmosDbKey, dbName) - .requestOptions(options) - .build(); + final CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() + .key(cosmosDbKey) + .endpoint(cosmosDbUri) + .consistencyLevel(ConsistencyLevel.CONSISTENT_PREFIX); + return CosmosDBConfig.builder() + .database(dbName) + .cosmosClientBuilder(cosmosClientBuilder) + .build(); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIT.java index c445b25be9ce..154a19dabb56 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIT.java @@ -2,9 +2,9 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.PartitionKey; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.cosmos.CosmosException; +import com.azure.cosmos.models.PartitionKey; +import com.azure.spring.data.cosmos.CosmosDBFactory; import com.azure.spring.data.cosmos.common.PageTestUtils; import com.azure.spring.data.cosmos.common.ResponseDiagnosticsTestUtils; import com.azure.spring.data.cosmos.config.CosmosDBConfig; @@ -38,7 +38,20 @@ import java.util.List; import java.util.UUID; -import static com.azure.spring.data.cosmos.common.TestConstants.*; +import static com.azure.spring.data.cosmos.common.TestConstants.ADDRESSES; +import static com.azure.spring.data.cosmos.common.TestConstants.FIRST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.HOBBIES; +import static com.azure.spring.data.cosmos.common.TestConstants.ID_1; +import static com.azure.spring.data.cosmos.common.TestConstants.ID_2; +import static com.azure.spring.data.cosmos.common.TestConstants.ID_3; +import static com.azure.spring.data.cosmos.common.TestConstants.LAST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.NEW_FIRST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.NEW_LAST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.NOT_EXIST_ID; +import static com.azure.spring.data.cosmos.common.TestConstants.PAGE_SIZE_1; +import static com.azure.spring.data.cosmos.common.TestConstants.PAGE_SIZE_2; +import static com.azure.spring.data.cosmos.common.TestConstants.PAGE_SIZE_3; +import static com.azure.spring.data.cosmos.common.TestConstants.UPDATED_FIRST_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -78,7 +91,7 @@ public class CosmosTemplateIT { @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - final CosmosDbFactory cosmosDbFactory = new CosmosDbFactory(dbConfig); + final CosmosDBFactory cosmosDbFactory = new CosmosDBFactory(dbConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = new CosmosEntityInformation<>(Person.class); @@ -93,7 +106,7 @@ public void setUp() throws ClassNotFoundException { initialized = true; } - insertedPerson = cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, null); + insertedPerson = cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, new PartitionKey(TEST_PERSON.getLastName())); } @After @@ -117,7 +130,7 @@ public void testFindAll() { final List result = cosmosTemplate.findAll(Person.class.getSimpleName(), Person.class); assertThat(result.size()).isEqualTo(1); assertThat(result.get(0)).isEqualTo(TEST_PERSON); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -127,7 +140,7 @@ public void testFindById() { final Person result = cosmosTemplate.findById(Person.class.getSimpleName(), TEST_PERSON.getId(), Person.class); assertEquals(result, TEST_PERSON); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); @@ -146,7 +159,7 @@ public void testFindByMultiIds() { final List ids = Lists.newArrayList(ID_1, ID_2, ID_3); final List result = cosmosTemplate.findByIds(ids, Person.class, containerName); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); @@ -167,12 +180,9 @@ public void testUpsertNewDocument() { final Person newPerson = new Person(TEST_PERSON.getId(), firstName, NEW_FIRST_NAME, null, null); - final Person person = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), - newPerson, - new PartitionKey(personInfo.getPartitionKeyFieldValue(newPerson))); + final Person person = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), newPerson); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); assertEquals(person.getFirstName(), firstName); @@ -184,8 +194,7 @@ public void testUpdateWithReturnEntity() { TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses()); updated.set_etag(insertedPerson.get_etag()); - final Person updatedPerson = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), - updated, null); + final Person updatedPerson = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), updated); final Person findPersonById = cosmosTemplate.findById(Person.class.getSimpleName(), updatedPerson.getId(), Person.class); @@ -200,11 +209,9 @@ public void testUpdate() { TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses()); updated.set_etag(insertedPerson.get_etag()); - final Person person = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), - updated, null); + final Person person = cosmosTemplate.upsertAndReturnEntity(Person.class.getSimpleName(), updated); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); assertEquals(person, updated); @@ -217,11 +224,11 @@ public void testOptimisticLockWhenUpdatingWithWrongEtag() { updated.set_etag(WRONG_ETAG); try { - cosmosTemplate.upsert(Person.class.getSimpleName(), updated, null); + cosmosTemplate.upsert(Person.class.getSimpleName(), updated); } catch (CosmosDBAccessException e) { - assertThat(e.getCosmosClientException()).isNotNull(); - final Throwable cosmosClientException = e.getCosmosClientException(); - assertThat(cosmosClientException).isInstanceOf(CosmosClientException.class); + assertThat(e.getCosmosException()).isNotNull(); + final Throwable cosmosClientException = e.getCosmosException(); + assertThat(cosmosClientException).isInstanceOf(CosmosException.class); assertThat(cosmosClientException.getMessage()).contains(PRECONDITION_IS_NOT_MET); final Person unmodifiedPerson = cosmosTemplate.findById(Person.class.getSimpleName(), @@ -241,13 +248,12 @@ public void testDeleteById() { cosmosTemplate.deleteById(Person.class.getSimpleName(), TEST_PERSON.getId(), new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final List result = cosmosTemplate.findAll(Person.class); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); assertThat(result.size()).isEqualTo(1); @@ -259,20 +265,19 @@ public void testCountByContainer() { final long prevCount = cosmosTemplate.count(containerName); assertThat(prevCount).isEqualTo(1); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); final long newCount = cosmosTemplate.count(containerName); assertThat(newCount).isEqualTo(2); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -282,18 +287,17 @@ public void testCountByQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", Collections.singletonList(TEST_PERSON_2.getFirstName())); final DocumentQuery query = new DocumentQuery(criteria); - final long count = cosmosTemplate.count(query, Person.class, containerName); + final long count = cosmosTemplate.count(query, containerName); assertThat(count).isEqualTo(1); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -303,8 +307,7 @@ public void testFindAllPageableMultiPages() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final CosmosPageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_1, null); @@ -313,8 +316,7 @@ public void testFindAllPageableMultiPages() { assertThat(page1.getContent().size()).isEqualTo(PAGE_SIZE_1); PageTestUtils.validateNonLastPage(page1, PAGE_SIZE_1); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); @@ -323,8 +325,7 @@ public void testFindAllPageableMultiPages() { assertThat(page2.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(page2, PAGE_SIZE_1); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -334,8 +335,7 @@ public void testPaginationQuery() { cosmosTemplate.insert(TEST_PERSON_2, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2))); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", @@ -347,8 +347,7 @@ public void testPaginationQuery() { assertThat(page.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(page, page.getContent().size()); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -360,8 +359,7 @@ public void testFindAllWithPageableAndSort() { cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3))); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); final Sort sort = Sort.by(Sort.Direction.DESC, "firstName"); @@ -376,8 +374,7 @@ public void testFindAllWithPageableAndSort() { assertThat(result.get(1).getFirstName()).isEqualTo(NEW_FIRST_NAME); assertThat(result.get(2).getFirstName()).isEqualTo(FIRST_NAME); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIllegalTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIllegalTest.java index b569f8d21159..5709bfc62ca7 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIllegalTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIllegalTest.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; import com.azure.spring.data.cosmos.core.query.DocumentQuery; @@ -20,7 +20,6 @@ import java.lang.reflect.Method; import java.util.Arrays; -@SuppressWarnings("unchecked") @RunWith(MockitoJUnitRunner.class) public class CosmosTemplateIllegalTest { private static final String NULL_STR = null; @@ -95,7 +94,7 @@ public void findByCollIdIllegalArgsShouldFail() throws NoSuchMethodException { /** * Check IllegalArgumentException is thrown for illegal parameters - * @param method + * @param method method type * @param args Method invocation parameters */ private void checkIllegalArgument(Method method, Object... args) { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplatePartitionIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplatePartitionIT.java index b72787b917ca..11c1ee2ca6c1 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplatePartitionIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplatePartitionIT.java @@ -3,8 +3,8 @@ package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.PartitionKey; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.cosmos.models.PartitionKey; +import com.azure.spring.data.cosmos.CosmosDBFactory; import com.azure.spring.data.cosmos.common.PageTestUtils; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; @@ -34,7 +34,20 @@ import java.util.List; import java.util.UUID; -import static com.azure.spring.data.cosmos.common.TestConstants.*; +import static com.azure.spring.data.cosmos.common.TestConstants.ADDRESSES; +import static com.azure.spring.data.cosmos.common.TestConstants.FIRST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.HOBBIES; +import static com.azure.spring.data.cosmos.common.TestConstants.ID_1; +import static com.azure.spring.data.cosmos.common.TestConstants.ID_2; +import static com.azure.spring.data.cosmos.common.TestConstants.LAST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.NEW_FIRST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.NEW_LAST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.NOT_EXIST_ID; +import static com.azure.spring.data.cosmos.common.TestConstants.PAGE_SIZE_1; +import static com.azure.spring.data.cosmos.common.TestConstants.PAGE_SIZE_2; +import static com.azure.spring.data.cosmos.common.TestConstants.PROPERTY_ID; +import static com.azure.spring.data.cosmos.common.TestConstants.PROPERTY_LAST_NAME; +import static com.azure.spring.data.cosmos.common.TestConstants.UPDATED_FIRST_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; @@ -60,7 +73,7 @@ public class CosmosTemplatePartitionIT { @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - final CosmosDbFactory cosmosDbFactory = new CosmosDbFactory(dbConfig); + final CosmosDBFactory cosmosDbFactory = new CosmosDBFactory(dbConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = new CosmosEntityInformation<>(PartitionPerson.class); @@ -137,8 +150,7 @@ public void testUpsertNewDocumentPartition() { final String partitionKeyValue = newPerson.getLastName(); final PartitionPerson partitionPerson = - cosmosTemplate.upsertAndReturnEntity(PartitionPerson.class.getSimpleName(), newPerson, - new PartitionKey(partitionKeyValue)); + cosmosTemplate.upsertAndReturnEntity(PartitionPerson.class.getSimpleName(), newPerson); final List result = cosmosTemplate.findAll(PartitionPerson.class); @@ -151,8 +163,7 @@ public void testUpdatePartition() { final PartitionPerson updated = new PartitionPerson(TEST_PERSON.getId(), UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses()); final PartitionPerson partitionPerson = - cosmosTemplate.upsertAndReturnEntity(PartitionPerson.class.getSimpleName(), updated, - new PartitionKey(updated.getLastName())); + cosmosTemplate.upsertAndReturnEntity(PartitionPerson.class.getSimpleName(), updated); assertEquals(partitionPerson, updated); } @@ -194,7 +205,7 @@ public void testCountForPartitionedCollectionByQuery() { Arrays.asList(TEST_PERSON_2.getFirstName())); final DocumentQuery query = new DocumentQuery(criteria); - final long count = cosmosTemplate.count(query, PartitionPerson.class, containerName); + final long count = cosmosTemplate.count(query, containerName); assertThat(count).isEqualTo(1); } @@ -204,7 +215,7 @@ public void testNonExistFieldValue() { Arrays.asList("non-exist-first-name")); final DocumentQuery query = new DocumentQuery(criteria); - final long count = cosmosTemplate.count(query, PartitionPerson.class, containerName); + final long count = cosmosTemplate.count(query, containerName); assertThat(count).isEqualTo(0); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateUnitTest.java index f183b45b3764..9ab3d7a72c0d 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateUnitTest.java @@ -3,7 +3,8 @@ package com.azure.spring.data.cosmos.core; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.spring.data.cosmos.CosmosDBFactory; import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import org.junit.Test; @@ -15,8 +16,13 @@ public class CosmosTemplateUnitTest { @Test(expected = IllegalArgumentException.class) public void rejectNullDbFactory() { - final CosmosDBConfig dbConfig = CosmosDBConfig.builder("", "", TestConstants.DB_NAME).build(); - final CosmosDbFactory cosmosDbFactory = new CosmosDbFactory(dbConfig); + final CosmosDBConfig dbConfig = CosmosDBConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint("") + .key("")) + .database(TestConstants.DB_NAME) + .build(); + final CosmosDBFactory cosmosDbFactory = new CosmosDBFactory(dbConfig); new CosmosTemplate(cosmosDbFactory, null, TestConstants.DB_NAME); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java index 46c056d6ac94..939e1bcaed91 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java @@ -2,10 +2,10 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosKeyCredential; -import com.azure.data.cosmos.PartitionKey; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.core.credential.AzureKeyCredential; +import com.azure.cosmos.CosmosException; +import com.azure.cosmos.models.PartitionKey; +import com.azure.spring.data.cosmos.CosmosDBFactory; import com.azure.spring.data.cosmos.common.ResponseDiagnosticsTestUtils; import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.config.CosmosDBConfig; @@ -18,9 +18,12 @@ import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.Assertions; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -35,14 +38,12 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; -@SuppressWarnings("unchecked") @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestRepositoryConfig.class) public class ReactiveCosmosTemplateIT { @@ -68,10 +69,13 @@ public class ReactiveCosmosTemplateIT { @Value("${cosmosdb.secondaryKey}") private String cosmosDbSecondaryKey; + @Value("${cosmosdb.key}") + private String cosmosDbKey; + private static ReactiveCosmosTemplate cosmosTemplate; private static String containerName; private static CosmosEntityInformation personInfo; - private static CosmosKeyCredential cosmosKeyCredential; + private static AzureKeyCredential azureKeyCredential; private static boolean initialized; @@ -87,8 +91,9 @@ public class ReactiveCosmosTemplateIT { @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - cosmosKeyCredential = new CosmosKeyCredential(dbConfig.getKey()); - final CosmosDbFactory dbFactory = new CosmosDbFactory(dbConfig); + azureKeyCredential = new AzureKeyCredential(cosmosDbKey); + dbConfig.getCosmosClientBuilder().credential(azureKeyCredential); + final CosmosDBFactory dbFactory = new CosmosDBFactory(dbConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = new CosmosEntityInformation<>(Person.class); @@ -98,8 +103,9 @@ public void setUp() throws ClassNotFoundException { final MappingCosmosConverter dbConverter = new MappingCosmosConverter(mappingContext, null); - cosmosTemplate = new ReactiveCosmosTemplate(dbFactory, dbConverter, dbConfig.getDatabase()); - cosmosTemplate.createContainerIfNotExists(personInfo).block().container(); + cosmosTemplate = new ReactiveCosmosTemplate(dbFactory, dbConverter, + dbConfig.getDatabase()); + cosmosTemplate.createContainerIfNotExists(personInfo).block(); initialized = true; } @@ -110,9 +116,8 @@ public void setUp() throws ClassNotFoundException { @After public void cleanup() { // Reset master key - cosmosKeyCredential.key(dbConfig.getKey()); - cosmosTemplate.deleteAll(Person.class.getSimpleName(), - personInfo.getPartitionKeyFieldName()).block(); + azureKeyCredential.update(cosmosDbKey); + cosmosTemplate.deleteAll(Person.class.getSimpleName(), Person.class).block(); } @AfterClass @@ -124,14 +129,9 @@ public static void afterClassCleanup() { public void testInsertDuplicateId() { final Mono insertMono = cosmosTemplate.insert(TEST_PERSON, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); - final TestSubscriber testSubscriber = new TestSubscriber<>(); - insertMono.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(); - testSubscriber.assertNotComplete(); - testSubscriber.assertTerminated(); - assertThat(testSubscriber.errors()).hasSize(1); - assertThat(((List) testSubscriber.getEvents().get(1)).get(0)) - .isInstanceOf(CosmosDBAccessException.class); + StepVerifier.create(insertMono) + .expectError(CosmosDBAccessException.class) + .verify(); } @Test @@ -142,14 +142,14 @@ public void testFindByID() { StepVerifier.create(findById) .consumeNextWith(actual -> Assert.assertEquals(actual, TEST_PERSON)) .verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @Test public void testFindByIDBySecondaryKey() { - cosmosKeyCredential.key(cosmosDbSecondaryKey); + azureKeyCredential.update(cosmosDbSecondaryKey); final Mono findById = cosmosTemplate.findById(Person.class.getSimpleName(), TEST_PERSON.getId(), Person.class); @@ -158,7 +158,7 @@ public void testFindByIDBySecondaryKey() { Assert.assertThat(actual.getLastName(), is(equalTo(TEST_PERSON.getLastName()))); }).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -169,7 +169,7 @@ public void testFindAll() { Person.class); StepVerifier.create(flux).expectNextCount(1).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -181,7 +181,7 @@ public void testFindByIdWithContainerName() { .consumeNextWith(actual -> Assert.assertEquals(actual, TEST_PERSON)) .verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -192,21 +192,21 @@ public void testInsert() { new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3)))) .expectNext(TEST_PERSON_3).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } @Test public void testInsertBySecondaryKey() { - cosmosKeyCredential.key(cosmosDbSecondaryKey); + azureKeyCredential.update(cosmosDbSecondaryKey); StepVerifier.create(cosmosTemplate.insert(TEST_PERSON_3, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3)))) .expectNext(TEST_PERSON_3).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } @Test @@ -215,9 +215,9 @@ public void testInsertWithContainerName() { new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2)))) .expectNext(TEST_PERSON_2).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } @Test @@ -227,30 +227,31 @@ public void testUpsert() { final ArrayList hobbies = new ArrayList<>(p.getHobbies()); hobbies.add("more code"); p.setHobbies(hobbies); - final Mono upsert = cosmosTemplate.upsert(p, - new PartitionKey(personInfo.getPartitionKeyFieldValue(p))); + final Mono upsert = cosmosTemplate.upsert(p); StepVerifier.create(upsert).expectNextCount(1).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } @Test public void testOptimisticLockWhenUpdatingWithWrongEtag() { final Person updated = new Person(TEST_PERSON.getId(), TestConstants.UPDATED_FIRST_NAME, - TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses()); + TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), + TEST_PERSON.getShippingAddresses()); updated.set_etag(WRONG_ETAG); try { - cosmosTemplate.upsert(updated, new PartitionKey(personInfo.getPartitionKeyFieldValue(updated))).block(); + cosmosTemplate.upsert(updated).block(); } catch (CosmosDBAccessException cosmosDbAccessException) { - assertThat(cosmosDbAccessException.getCosmosClientException()).isNotNull(); - final Throwable cosmosClientException = cosmosDbAccessException.getCosmosClientException(); - assertThat(cosmosClientException).isInstanceOf(CosmosClientException.class); + assertThat(cosmosDbAccessException.getCosmosException()).isNotNull(); + final Throwable cosmosClientException = cosmosDbAccessException.getCosmosException(); + assertThat(cosmosClientException).isInstanceOf(CosmosException.class); assertThat(cosmosClientException.getMessage()).contains(PRECONDITION_IS_NOT_MET); - final Mono unmodifiedPerson = cosmosTemplate.findById(Person.class.getSimpleName(), + final Mono unmodifiedPerson = + cosmosTemplate.findById(Person.class.getSimpleName(), TEST_PERSON.getId(), Person.class); StepVerifier.create(unmodifiedPerson).expectNextMatches(person -> person.getFirstName().equals(insertedPerson.getFirstName())).verifyComplete(); @@ -261,18 +262,17 @@ public void testOptimisticLockWhenUpdatingWithWrongEtag() { @Test public void testUpsertBySecondaryKey() { - cosmosKeyCredential.key(cosmosDbSecondaryKey); + azureKeyCredential.update(cosmosDbSecondaryKey); final Person p = TEST_PERSON_2; final ArrayList hobbies = new ArrayList<>(p.getHobbies()); hobbies.add("more code"); p.setHobbies(hobbies); - final Mono upsert = cosmosTemplate.upsert(p, - new PartitionKey(personInfo.getPartitionKeyFieldValue(p))); + final Mono upsert = cosmosTemplate.upsert(p); StepVerifier.create(upsert).expectNextCount(1).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } @Test @@ -281,13 +281,12 @@ public void testUpsertWithContainerName() { final ArrayList hobbies = new ArrayList<>(p.getHobbies()); hobbies.add("more code"); p.setHobbies(hobbies); - final Mono upsert = cosmosTemplate.upsert(Person.class.getSimpleName(), p, - new PartitionKey(personInfo.getPartitionKeyFieldValue(p))); + final Mono upsert = cosmosTemplate.upsert(Person.class.getSimpleName(), p); StepVerifier.create(upsert).expectNextCount(1).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); } @Test @@ -295,39 +294,39 @@ public void testDeleteById() { cosmosTemplate.insert(TEST_PERSON_4, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_4))).block(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); Flux flux = cosmosTemplate.findAll(Person.class.getSimpleName(), Person.class); StepVerifier.create(flux).expectNextCount(2).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); + final Mono voidMono = cosmosTemplate.deleteById(Person.class.getSimpleName(), TEST_PERSON_4.getId(), new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_4))); StepVerifier.create(voidMono).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNull(); + Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNotNull(); flux = cosmosTemplate.findAll(Person.class.getSimpleName(), Person.class); StepVerifier.create(flux).expectNextCount(1).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); + } @Test public void testDeleteByIdBySecondaryKey() { - cosmosKeyCredential.key(cosmosDbSecondaryKey); + azureKeyCredential.update(cosmosDbSecondaryKey); cosmosTemplate.insert(TEST_PERSON_4, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_4))).block(); Flux flux = cosmosTemplate.findAll(Person.class.getSimpleName(), Person.class); @@ -349,10 +348,9 @@ public void testFind() { Person.class.getSimpleName()); StepVerifier.create(personFlux).expectNextCount(1).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); } @Test @@ -363,37 +361,37 @@ public void testExists() { final Mono exists = cosmosTemplate.exists(query, Person.class, containerName); StepVerifier.create(exists).expectNext(true).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); } @Test public void testCount() { final Mono count = cosmosTemplate.count(containerName); - StepVerifier.create(count).expectNext((long) 1).verifyComplete(); + StepVerifier.create(count).expectNext((long)1).verifyComplete(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); } @Test public void testCountBySecondaryKey() { - cosmosKeyCredential.key(cosmosDbSecondaryKey); + azureKeyCredential.update(cosmosDbSecondaryKey); final Mono count = cosmosTemplate.count(containerName); - StepVerifier.create(count).expectNext((long) 1).verifyComplete(); + StepVerifier.create(count).expectNext((long)1).verifyComplete(); } @Test public void testInvalidSecondaryKey() { - cosmosKeyCredential.key("Invalid secondary key"); + azureKeyCredential.update("Invalid secondary key"); final Mono findById = cosmosTemplate.findById(Person.class.getSimpleName(), TEST_PERSON.getId(), Person.class); - StepVerifier.create(findById).expectError(IllegalArgumentException.class); + StepVerifier.create(findById) + .expectError(CosmosDBAccessException.class) + .verify(); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplatePartitionIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplatePartitionIT.java index 934b6bb546fd..d0ec0e2dad04 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplatePartitionIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplatePartitionIT.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core; -import com.azure.data.cosmos.PartitionKey; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.cosmos.models.PartitionKey; +import com.azure.spring.data.cosmos.CosmosDBFactory; import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; @@ -14,7 +14,11 @@ import com.azure.spring.data.cosmos.domain.PartitionPerson; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.domain.EntityScanner; @@ -56,7 +60,7 @@ public class ReactiveCosmosTemplatePartitionIT { @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - final CosmosDbFactory dbFactory = new CosmosDbFactory(dbConfig); + final CosmosDBFactory dbFactory = new CosmosDBFactory(dbConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = @@ -77,8 +81,7 @@ public void setUp() throws ClassNotFoundException { @After public void cleanup() { - cosmosTemplate.deleteAll(PartitionPerson.class.getSimpleName(), - personInfo.getPartitionKeyFieldName()).block(); + cosmosTemplate.deleteAll(PartitionPerson.class.getSimpleName(), PartitionPerson.class).block(); } @AfterClass @@ -124,8 +127,7 @@ public void testUpsertNewDocumentPartition() { firstName, TestConstants.NEW_LAST_NAME, null, null); final String partitionKeyValue = newPerson.getLastName(); - final Mono upsert = cosmosTemplate.upsert(newPerson, - new PartitionKey(partitionKeyValue)); + final Mono upsert = cosmosTemplate.upsert(newPerson); StepVerifier.create(upsert).expectNextCount(1).verifyComplete(); } @@ -134,7 +136,7 @@ public void testUpdateWithPartition() { final PartitionPerson updated = new PartitionPerson(TEST_PERSON.getId(), TestConstants.UPDATED_FIRST_NAME, TEST_PERSON.getLastName(), TEST_PERSON.getHobbies(), TEST_PERSON.getShippingAddresses()); - cosmosTemplate.upsert(updated, new PartitionKey(updated.getLastName())).block(); + cosmosTemplate.upsert(updated).block(); final PartitionPerson person = cosmosTemplate .findAll(PartitionPerson.class.getSimpleName(), PartitionPerson.class) @@ -162,7 +164,7 @@ public void testDeleteAll() { StepVerifier.create(cosmosTemplate.findAll(PartitionPerson.class)).expectNextCount(2).verifyComplete(); final CosmosEntityInformation personInfo = new CosmosEntityInformation<>(PartitionPerson.class); - cosmosTemplate.deleteAll(containerName, personInfo.getPartitionKeyFieldName()).block(); + cosmosTemplate.deleteAll(containerName, PartitionPerson.class).block(); StepVerifier.create(cosmosTemplate.findAll(PartitionPerson.class)) .expectNextCount(0) .verifyComplete(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/converter/MappingCosmosConverterUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/converter/MappingCosmosConverterUnitTest.java index b690633be817..dc02b2a1ffb6 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/converter/MappingCosmosConverterUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/converter/MappingCosmosConverterUnitTest.java @@ -2,15 +2,16 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.core.converter; -import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; +import com.azure.spring.data.cosmos.core.convert.ObjectMapperFactory; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.domain.Address; import com.azure.spring.data.cosmos.domain.Importance; import com.azure.spring.data.cosmos.domain.Memo; -import org.json.JSONObject; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,23 +50,23 @@ public void setUp() { @Test public void covertAddressToDocumentCorrectly() { final Address testAddress = new Address(TestConstants.POSTAL_CODE, TestConstants.CITY, TestConstants.STREET); - final CosmosItemProperties cosmosItemProperties = mappingCosmosConverter.writeCosmosItemProperties(testAddress); + final JsonNode jsonNode = mappingCosmosConverter.writeJsonNode(testAddress); - assertThat(cosmosItemProperties.id()).isEqualTo(testAddress.getPostalCode()); - assertThat(cosmosItemProperties.getString(TestConstants.PROPERTY_CITY)).isEqualTo(testAddress.getCity()); - assertThat(cosmosItemProperties.getString(TestConstants.PROPERTY_STREET)).isEqualTo(testAddress.getStreet()); + assertThat(jsonNode.get("id").asText()).isEqualTo(testAddress.getPostalCode()); + assertThat(jsonNode.get(TestConstants.PROPERTY_CITY).asText()).isEqualTo(testAddress.getCity()); + assertThat(jsonNode.get(TestConstants.PROPERTY_STREET).asText()).isEqualTo(testAddress.getStreet()); } @Test public void convertDocumentToAddressCorrectly() { - final JSONObject jsonObject = new JSONObject(); - jsonObject.put(TestConstants.PROPERTY_CITY, TestConstants.CITY); - jsonObject.put(TestConstants.PROPERTY_STREET, TestConstants.STREET); + final ObjectNode objectNode = ObjectMapperFactory.getObjectMapper().createObjectNode(); + objectNode.put(TestConstants.PROPERTY_CITY, TestConstants.CITY); + objectNode.put(TestConstants.PROPERTY_STREET, TestConstants.STREET); + objectNode.put(TestConstants.PROPERTY_ID, TestConstants.POSTAL_CODE); - final CosmosItemProperties cosmosItemProperties = new CosmosItemProperties(jsonObject.toString()); - cosmosItemProperties.id(TestConstants.POSTAL_CODE); + final JsonNode jsonNode = mappingCosmosConverter.writeJsonNode(objectNode); - final Address address = mappingCosmosConverter.read(Address.class, cosmosItemProperties); + final Address address = mappingCosmosConverter.read(Address.class, jsonNode); assertThat(address.getPostalCode()).isEqualTo(TestConstants.POSTAL_CODE); assertThat(address.getCity()).isEqualTo(TestConstants.CITY); @@ -76,28 +77,28 @@ public void convertDocumentToAddressCorrectly() { public void canWritePojoWithDateToDocument() throws ParseException { final Memo memo = new Memo(TestConstants.ID_1, TestConstants.MESSAGE, DATE.parse(TestConstants.DATE_STRING), Importance.NORMAL); - final CosmosItemProperties cosmosItemProperties = mappingCosmosConverter.writeCosmosItemProperties(memo); + final JsonNode jsonNode = mappingCosmosConverter.writeJsonNode(memo); - assertThat(cosmosItemProperties.id()).isEqualTo(memo.getId()); - assertThat(cosmosItemProperties.getString(TestConstants.PROPERTY_MESSAGE)).isEqualTo(memo.getMessage()); - assertThat(cosmosItemProperties.getLong(TestConstants.PROPERTY_DATE)).isEqualTo(memo.getDate().getTime()); + assertThat(jsonNode.get(TestConstants.PROPERTY_ID).asText()).isEqualTo(memo.getId()); + assertThat(jsonNode.get(TestConstants.PROPERTY_MESSAGE).asText()).isEqualTo(memo.getMessage()); + assertThat(jsonNode.get(TestConstants.PROPERTY_DATE).asLong()).isEqualTo(memo.getDate().getTime()); } @Test public void canReadPojoWithDateFromDocument() throws ParseException { - final JSONObject jsonObject = new JSONObject(); + final ObjectNode jsonObject = ObjectMapperFactory.getObjectMapper().createObjectNode(); jsonObject.put(TestConstants.PROPERTY_MESSAGE, TestConstants.MESSAGE); final long date = DATE.parse(TestConstants.DATE_STRING).getTime(); jsonObject.put(TestConstants.PROPERTY_DATE, date); + jsonObject.put(TestConstants.PROPERTY_ID, TestConstants.ID_1); - final CosmosItemProperties cosmosItemProperties = new CosmosItemProperties(jsonObject.toString()); - cosmosItemProperties.id(TestConstants.ID_1); + final JsonNode jsonNode = mappingCosmosConverter.writeJsonNode(jsonObject); - final Memo memo = mappingCosmosConverter.read(Memo.class, cosmosItemProperties); - assertThat(cosmosItemProperties.id()).isEqualTo(memo.getId()); - assertThat(cosmosItemProperties.getString(TestConstants.PROPERTY_MESSAGE)).isEqualTo(TestConstants.MESSAGE); - assertThat(cosmosItemProperties.getLong(TestConstants.PROPERTY_DATE)).isEqualTo(date); + final Memo memo = mappingCosmosConverter.read(Memo.class, jsonNode); + assertThat(jsonNode.get("id").asText()).isEqualTo(memo.getId()); + assertThat(jsonNode.get(TestConstants.PROPERTY_MESSAGE).asText()).isEqualTo(TestConstants.MESSAGE); + assertThat(jsonNode.get(TestConstants.PROPERTY_DATE).asLong()).isEqualTo(date); } @Test diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/PageablePerson.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/PageablePerson.java index ad7d2197baf4..f1e0ac86acb7 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/PageablePerson.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/PageablePerson.java @@ -6,14 +6,13 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; -import com.azure.spring.data.cosmos.common.TestConstants; import org.springframework.data.annotation.Version; import java.util.List; import java.util.Objects; @Document() -@DocumentIndexingPolicy(includePaths = TestConstants.ORDER_BY_STRING_PATH) +@DocumentIndexingPolicy() public class PageablePerson { private String id; private String firstName; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Person.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Person.java index 3a4a64b55ed0..2fa20bf67bce 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Person.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Person.java @@ -6,14 +6,13 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; -import com.azure.spring.data.cosmos.common.TestConstants; import org.springframework.data.annotation.Version; import java.util.List; import java.util.Objects; @Document() -@DocumentIndexingPolicy(includePaths = TestConstants.ORDER_BY_STRING_PATH) +@DocumentIndexingPolicy() public class Person { private String id; private String firstName; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Project.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Project.java index 77b75e914258..e02dab6b3725 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Project.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Project.java @@ -5,13 +5,12 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; -import com.azure.spring.data.cosmos.common.TestConstants; import org.springframework.data.annotation.Id; import java.util.Objects; @Document() -@DocumentIndexingPolicy(includePaths = TestConstants.ORDER_BY_STRING_PATH) +@DocumentIndexingPolicy() public class Project { @Id diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Question.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Question.java index 2c1c9f6a6384..db7269e9830b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Question.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Question.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.domain; -import com.azure.data.cosmos.IndexingMode; +import com.azure.cosmos.models.IndexingMode; import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; @@ -12,7 +12,7 @@ import java.util.UUID; @Document -@DocumentIndexingPolicy(mode = IndexingMode.LAZY) +@DocumentIndexingPolicy(mode = IndexingMode.CONSISTENT) public class Question { @Id diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Role.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Role.java index 1e04be72330f..b80304e172e0 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Role.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Role.java @@ -2,29 +2,20 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.domain; -import com.azure.data.cosmos.IndexingMode; +import com.azure.cosmos.models.IndexingMode; +import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; -import com.azure.spring.data.cosmos.common.TestConstants; import org.springframework.data.annotation.Id; import java.util.Objects; @DocumentIndexingPolicy( - mode = IndexingMode.LAZY, - automatic = TestConstants.INDEXINGPOLICY_AUTOMATIC, - includePaths = { - TestConstants.INCLUDEDPATH_0, - TestConstants.INCLUDEDPATH_1, - TestConstants.INCLUDEDPATH_2, - }, - excludePaths = { - TestConstants.EXCLUDEDPATH_0, - TestConstants.EXCLUDEDPATH_1, - }) -@Document(collection = TestConstants.ROLE_COLLECTION_NAME, - autoCreateCollection = false) + mode = IndexingMode.CONSISTENT, + automatic = TestConstants.INDEXING_POLICY_AUTOMATIC) +@Document(container = TestConstants.ROLE_COLLECTION_NAME, + autoCreateContainer = false) public class Role { @Id String id; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SortedProject.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SortedProject.java index 4bf8d7528f75..d1fa4472029e 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SortedProject.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SortedProject.java @@ -5,13 +5,12 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; -import com.azure.spring.data.cosmos.common.TestConstants; import org.springframework.data.annotation.Id; import java.util.Objects; @Document() -@DocumentIndexingPolicy(includePaths = TestConstants.ORDER_BY_STRING_PATH) +@DocumentIndexingPolicy() public class SortedProject { @Id diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SpELBeanStudent.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SpELBeanStudent.java index d426b7c241e7..c847ff289555 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SpELBeanStudent.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SpELBeanStudent.java @@ -7,7 +7,7 @@ import java.util.Objects; -@Document(collection = "#{@dynamicContainer.getContainerName()}") +@Document(container = "#{@dynamicContainer.getContainerName()}") public class SpELBeanStudent { private String id; private String firstName; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SpELPropertyStudent.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SpELPropertyStudent.java index 5d1a74296ad9..aab4c00198fb 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SpELPropertyStudent.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/SpELPropertyStudent.java @@ -7,7 +7,7 @@ import java.util.Objects; -@Document(collection = "${dynamic.collection.name}") +@Document(container = "${dynamic.collection.name}") public class SpELPropertyStudent { private String id; private String firstName; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Student.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Student.java index d3473617dcd7..82739641cc6a 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Student.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/Student.java @@ -4,11 +4,10 @@ package com.azure.spring.data.cosmos.domain; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; -import com.azure.spring.data.cosmos.common.TestConstants; import java.util.Objects; -@DocumentIndexingPolicy(includePaths = TestConstants.STARTSWITH_INCLUDEDPATH) +@DocumentIndexingPolicy() public class Student { private String id; private String firstName; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/TimeToLiveSample.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/TimeToLiveSample.java index 5c1a97acf7ab..581b546421e2 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/TimeToLiveSample.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/domain/TimeToLiveSample.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.domain; -import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.common.TestConstants; +import com.azure.spring.data.cosmos.core.mapping.Document; @Document(timeToLive = TestConstants.TIME_TO_LIVE) public class TimeToLiveSample { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerfConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerfConfiguration.java index d80a8c02da40..1e71ad3ab5a9 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerfConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerfConfiguration.java @@ -2,6 +2,7 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.performance; +import com.azure.cosmos.CosmosClientBuilder; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.performance.utils.Constants; @@ -23,6 +24,11 @@ public class PerfConfiguration extends AbstractCosmosConfiguration { @Bean public CosmosDBConfig getConfig() { - return CosmosDBConfig.builder(cosmosDbUri, cosmosDbKey, Constants.PERF_DATABASE_NAME).build(); + return CosmosDBConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(cosmosDbUri) + .key(cosmosDbKey)) + .database(Constants.PERF_DATABASE_NAME) + .build(); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerformanceCompare.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerformanceCompare.java index 14256feed345..009da215e7f1 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerformanceCompare.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerformanceCompare.java @@ -2,9 +2,9 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.performance; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.sync.CosmosSyncClient; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosException; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; import com.azure.spring.data.cosmos.performance.domain.PerfPerson; import com.azure.spring.data.cosmos.performance.repository.PerfPersonRepository; @@ -52,10 +52,10 @@ public class PerformanceCompare { private float acceptanceDiff; @Autowired - private CosmosSyncClient cosmosSyncClient; + private CosmosClient cosmosClient; @Autowired - private CosmosClient asyncClient; + private CosmosAsyncClient cosmosAsyncClient; @Autowired private PerfPersonRepository repository; @@ -65,16 +65,16 @@ public class PerformanceCompare { private static PerformanceReport report = new PerformanceReport(); @Before - public void setUp() throws CosmosClientException { + public void setUp() throws CosmosException { if (!hasInit) { - DatabaseUtils.createDatabase(cosmosSyncClient, Constants.PERF_DATABASE_NAME); - DatabaseUtils.createContainer(cosmosSyncClient, Constants.PERF_DATABASE_NAME, - Constants.SPRING_COLLECTION_NAME); - DatabaseUtils.createContainer(cosmosSyncClient, - Constants.PERF_DATABASE_NAME, Constants.SDK_COLLECTION_NAME); - - sdkService = new SdkService(cosmosSyncClient, Constants.PERF_DATABASE_NAME, - Constants.SDK_COLLECTION_NAME, asyncClient); + DatabaseUtils.createDatabase(cosmosClient, Constants.PERF_DATABASE_NAME); + DatabaseUtils.createContainer(cosmosClient, Constants.PERF_DATABASE_NAME, + Constants.SPRING_CONTAINER_NAME); + DatabaseUtils.createContainer(cosmosClient, + Constants.PERF_DATABASE_NAME, Constants.SDK_CONTAINER_NAME); + + sdkService = new SdkService(cosmosClient, Constants.PERF_DATABASE_NAME, + Constants.SDK_CONTAINER_NAME, cosmosAsyncClient); hasInit = true; } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/domain/PerfPerson.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/domain/PerfPerson.java index eb6e15ba1a07..12d5b4d425ba 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/domain/PerfPerson.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/domain/PerfPerson.java @@ -6,12 +6,11 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; import com.azure.spring.data.cosmos.performance.utils.Constants; -import com.azure.spring.data.cosmos.common.TestConstants; import java.util.Objects; -@Document(collection = Constants.SPRING_COLLECTION_NAME) -@DocumentIndexingPolicy(includePaths = TestConstants.ORDER_BY_STRING_PATH) +@Document(container = Constants.SPRING_CONTAINER_NAME) +@DocumentIndexingPolicy() public class PerfPerson { private String id; private String name; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/repository/PerfPersonRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/repository/PerfPersonRepository.java index 19cabb78bba7..510ff1696e3e 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/repository/PerfPersonRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/repository/PerfPersonRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.performance.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.performance.domain.PerfPerson; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Repository; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/service/SdkService.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/service/SdkService.java index b9fa8bb4d6b8..cac5122123ba 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/service/SdkService.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/service/SdkService.java @@ -2,11 +2,16 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.performance.service; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.sync.CosmosSyncClient; -import com.azure.spring.data.cosmos.performance.utils.DatabaseUtils; -import com.google.gson.Gson; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosException; +import com.azure.cosmos.models.CosmosItemRequestOptions; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.FeedResponse; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.performance.domain.PerfPerson; +import com.azure.spring.data.cosmos.performance.utils.DatabaseUtils; +import com.fasterxml.jackson.databind.JsonNode; import org.assertj.core.util.Lists; import org.springframework.data.domain.Sort; @@ -17,29 +22,25 @@ import java.util.stream.Collectors; public class SdkService { - private static Gson gson = new Gson(); - private final CosmosSyncClient cosmosSyncClient; + private final CosmosClient cosmosClient; private final String dbName; private final String containerName; - public SdkService(CosmosSyncClient client, String dbName, String containerName, CosmosClient asyncClient) { - this.cosmosSyncClient = client; + public SdkService(CosmosClient client, String dbName, String containerName, + CosmosAsyncClient cosmosAsyncClient) { + this.cosmosClient = client; this.dbName = dbName; this.containerName = containerName; } public PerfPerson save(PerfPerson person) { try { - final String personJson = gson.toJson(person); - final CosmosItemProperties personDoc = new CosmosItemProperties(personJson); - final CosmosItemProperties doc = cosmosSyncClient.getDatabase(dbName) - .getContainer(containerName) - .createItem(personDoc) - .properties(); - - return gson.fromJson(doc.toJson(), PerfPerson.class); + return cosmosClient.getDatabase(dbName) + .getContainer(containerName) + .createItem(person) + .getItem(); } catch (Exception e) { throw new IllegalStateException(e); // Runtime exception to fail directly } @@ -54,83 +55,85 @@ public List saveAll(Iterable personIterable) { public void delete(PerfPerson person) { try { - final String docLink = DatabaseUtils.getDocumentLink(dbName, containerName, person.getId()); - cosmosSyncClient.getDatabase(dbName) - .getContainer(containerName) - .getItem(person.getId(), PartitionKey.None) - .delete(new CosmosItemRequestOptions()); + final String docLink = DatabaseUtils.getDocumentLink(dbName, containerName, + person.getId()); + cosmosClient.getDatabase(dbName) + .getContainer(containerName) + .deleteItem(person.getId(), PartitionKey.NONE, + new CosmosItemRequestOptions()); - } catch (CosmosClientException e) { + } catch (CosmosException e) { throw new IllegalStateException(e); // Runtime exception to fail directly } } public void deleteAll(Iterable personIterable) { - personIterable.forEach(person -> delete(person)); + personIterable.forEach(this::delete); } - public CosmosItemProperties findById(String id) { - final Iterator> feedResponseIterator = - cosmosSyncClient.getDatabase(dbName) + public PerfPerson findById(String id) { + final Iterator> feedResponseIterator = + cosmosClient.getDatabase(dbName) .getContainer(containerName) .queryItems("SELECT * FROM " - + containerName - + " WHERE " - + containerName - + ".id='" - + id - + "'", new FeedOptions()); - CosmosItemProperties itemProperties = null; + + containerName + + " WHERE " + + containerName + + ".id='" + + id + + "'", new CosmosQueryRequestOptions(), PerfPerson.class) + .iterableByPage() + .iterator(); + PerfPerson perfPerson = null; if (feedResponseIterator.hasNext()) { - final List results = feedResponseIterator.next().results(); + final List results = feedResponseIterator.next().getResults(); if (!results.isEmpty()) { - itemProperties = results.get(0); + perfPerson = results.get(0); } } - return itemProperties; + return perfPerson; } public List findAllById(Iterable ids) { final String idsInList = String.join(",", - Arrays.asList(ids).stream().map(id -> "'" + id + "'").collect(Collectors.toList())); + Arrays.asList(ids).stream().map(id -> "'" + id + "'").collect(Collectors.toList())); final String sql = "SELECT * FROM " + containerName + " WHERE " + containerName + ".id IN (" - + idsInList + ")"; + + idsInList + ")"; - final FeedOptions feedOptions = new FeedOptions(); - feedOptions.enableCrossPartitionQuery(true); + final List docs = new ArrayList<>(); - final List docs = new ArrayList<>(); - - final Iterator> feedResponseIterator = cosmosSyncClient.getDatabase(dbName) + final Iterator> feedResponseIterator = + cosmosClient.getDatabase(dbName) .getContainer(containerName) - .queryItems(sql, feedOptions); + .queryItems(sql, new CosmosQueryRequestOptions(), PerfPerson.class) + .iterableByPage() + .iterator(); while (feedResponseIterator.hasNext()) { - final FeedResponse next = feedResponseIterator.next(); - docs.addAll(next.results()); + final FeedResponse next = feedResponseIterator.next(); + docs.addAll(next.getResults()); } - return fromDocuments(docs); + return docs; } public List findAll() { final String sql = "SELECT * FROM " + containerName; - final List docs = getCosmosItemPropertiesList(sql); - return fromDocuments(docs); + return getPerfPersonList(sql); } public boolean deleteAll() { final String sql = "SELECT * FROM " + containerName; - final List documents = getCosmosItemPropertiesList(sql); + final List documents = getPerfPersonList(sql); documents.forEach(document -> { try { - cosmosSyncClient.getDatabase(dbName) - .getContainer(containerName) - .getItem(document.id(), PartitionKey.None) - .delete(new CosmosItemRequestOptions().partitionKey(PartitionKey.None)); - } catch (CosmosClientException e) { + cosmosClient.getDatabase(dbName) + .getContainer(containerName) + .deleteItem(document.getId(), PartitionKey.NONE, + new CosmosItemRequestOptions()); + } catch (CosmosException e) { throw new IllegalStateException(e); } }); @@ -138,76 +141,72 @@ public boolean deleteAll() { return true; } - private List getCosmosItemPropertiesList(String sql) { - final List documents = new ArrayList<>(); - final Iterator> feedResponseIterator = - cosmosSyncClient.getDatabase(dbName) + private List getPerfPersonList(String sql, int size) { + final List documents = new ArrayList<>(); + final Iterator> feedResponseIterator = + cosmosClient.getDatabase(dbName) .getContainer(containerName) - .queryItems(sql, new FeedOptions().enableCrossPartitionQuery(true)); + .queryItems(sql, new CosmosQueryRequestOptions(), PerfPerson.class) + .iterableByPage(size) + .iterator(); while (feedResponseIterator.hasNext()) { - final FeedResponse next = feedResponseIterator.next(); - documents.addAll(next.results()); + final FeedResponse next = feedResponseIterator.next(); + documents.addAll(next.getResults()); } return documents; } + private List getPerfPersonList(String sql) { + // Pass default page size, which is 100 + return getPerfPersonList(sql, 100); + } + public List searchDocuments(Sort sort) { final Sort.Order order = sort.iterator().next(); // Only one Order supported final String sql = "SELECT * FROM " + containerName + " ORDER BY " + containerName + "." - + order.getProperty() + " " + order.getDirection().name(); - final List docs = getCosmosItemPropertiesList(sql); - - return fromDocuments(docs); + + order.getProperty() + " " + order.getDirection().name(); + return getPerfPersonList(sql); } public long count() { final String sql = "SELECT VALUE COUNT(1) FROM " + containerName; - final Iterator> feedResponseIterator = cosmosSyncClient.getDatabase(dbName) - .getContainer(containerName) - .queryItems(sql, new FeedOptions()); - final Object result = feedResponseIterator.next().results().get(0).get("_aggregate"); + final Iterator> feedResponseIterator = + cosmosClient.getDatabase(dbName) + .getContainer(containerName) + .queryItems(sql + , + new CosmosQueryRequestOptions(), JsonNode.class) + .iterableByPage() + .iterator(); - return result instanceof Integer ? Long.valueOf((Integer) result) : (Long) result; + return feedResponseIterator.next().getResults().get(0).get("_aggregate").asLong(); } public List findByName(String name) { final String sql = "SELECT * FROM " + containerName + " WHERE " + containerName + ".name='" - + name + "'"; - final Iterator result = getCosmosItemPropertiesList(sql).iterator(); - return fromDocuments(Lists.newArrayList(result)); + + name + "'"; + final Iterator result = getPerfPersonList(sql).iterator(); + return Lists.newArrayList(result); } public void queryTwoPages(int pageSize) { - final FeedOptions options = new FeedOptions(); - options.maxItemCount(pageSize); - options.requestContinuation(null); - - searchBySize(pageSize, options); - searchBySize(pageSize, options); + searchBySize(pageSize); + searchBySize(pageSize); } - private List searchBySize(int size, FeedOptions options) { + private List searchBySize(int size) { final String sql = "SELECT * FROM " + containerName; - final Iterator it = getCosmosItemPropertiesList(sql).iterator(); + final Iterator it = getPerfPersonList(sql, size).iterator(); final List entities = new ArrayList<>(); int i = 0; - while (it.hasNext() - && i++ < size) { - // This convert here is in order to mock data conversion in real use case, in order to compare with - // Spring Data mapping - final CosmosItemProperties d = it.next(); - final PerfPerson entity = gson.fromJson(d.toJson(), PerfPerson.class); - entities.add(entity); + while (it.hasNext() && i++ < size) { + final PerfPerson perfPerson = it.next(); + entities.add(perfPerson); } count(); // Mock same behavior with Spring pageable query, requires total elements count return entities; } - - private List fromDocuments(List documents) { - return documents.stream().map(d -> gson.fromJson(d.toJson(), PerfPerson.class)) - .collect(Collectors.toList()); - } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/utils/Constants.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/utils/Constants.java index 24061701bdb9..904e399372e2 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/utils/Constants.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/utils/Constants.java @@ -4,6 +4,6 @@ public class Constants { public static final String PERF_DATABASE_NAME = "perf_database"; - public static final String SPRING_COLLECTION_NAME = "spring_perf_coll"; - public static final String SDK_COLLECTION_NAME = "sdk_perf_coll"; + public static final String SPRING_CONTAINER_NAME = "spring_perf_container"; + public static final String SDK_CONTAINER_NAME = "sdk_perf_container"; } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/utils/DatabaseUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/utils/DatabaseUtils.java index 14ced00fcd8f..bc210f9e1f32 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/utils/DatabaseUtils.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/utils/DatabaseUtils.java @@ -2,45 +2,45 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.performance.utils; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.sync.CosmosSyncClient; +import com.azure.cosmos.CosmosClient; +import com.azure.cosmos.CosmosException; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.IncludedPath; +import com.azure.cosmos.models.IndexingPolicy; +import com.azure.cosmos.models.PartitionKeyDefinition; import java.util.Collections; import static com.azure.spring.data.cosmos.common.TestConstants.ORDER_BY_STRING_PATH; public class DatabaseUtils { - public static void createDatabase(CosmosSyncClient documentClient, String databaseName) - throws CosmosClientException { + public static void createDatabase(CosmosClient cosmosClient, String databaseName) + throws CosmosException { try { // Can use sync api once ready - documentClient.getDatabase(databaseName).delete(); + cosmosClient.getDatabase(databaseName).delete(); } catch (Exception e) { // Ignore delete failure } - documentClient.createDatabase(databaseName); + cosmosClient.createDatabase(databaseName); } - public static void deleteContainer(CosmosSyncClient documentClient, String databaseName, String containerName) - throws CosmosClientException { - final RequestOptions requestOptions = new RequestOptions(); - requestOptions.setOfferThroughput(1000); - - documentClient.getDatabase(databaseName).getContainer(containerName).delete(); + public static void deleteContainer(CosmosClient cosmosClient, String databaseName, String containerName) + throws CosmosException { + cosmosClient.getDatabase(databaseName).getContainer(containerName).delete(); } - public static void createContainer(CosmosSyncClient documentClient, String databaseName, String containerName) - throws CosmosClientException { + public static void createContainer(CosmosClient cosmosClient, String databaseName, String containerName) + throws CosmosException { final CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, - new PartitionKeyDefinition().paths(Collections.singletonList("/mypk"))); + new PartitionKeyDefinition().setPaths(Collections.singletonList("/mypk"))); final IndexingPolicy policy = new IndexingPolicy(); policy.setIncludedPaths(Collections.singletonList(new IncludedPath(ORDER_BY_STRING_PATH))); - containerProperties.indexingPolicy(policy); + containerProperties.setIndexingPolicy(policy); - documentClient.getDatabase(databaseName).createContainer(containerProperties); + cosmosClient.getDatabase(databaseName).createContainer(containerProperties); } public static String getDocumentLink(String databaseName, String containerName, Object documentId) { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/CosmosAnnotationUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/CosmosAnnotationUnitTest.java index 2488069f1d14..e8c055618b8b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/CosmosAnnotationUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/CosmosAnnotationUnitTest.java @@ -2,15 +2,14 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository; -import com.azure.data.cosmos.IndexingPolicy; +import com.azure.cosmos.models.IndexingPolicy; +import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.DocumentIndexingPolicy; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.common.TestUtils; import com.azure.spring.data.cosmos.domain.NoDBAnnotationPerson; import com.azure.spring.data.cosmos.domain.Role; import com.azure.spring.data.cosmos.domain.TimeToLiveSample; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.junit.Before; import org.junit.Test; import org.springframework.util.Assert; @@ -40,9 +39,9 @@ public void testDefaultIndexingPolicyAnnotation() { // ContainerName, RequestUnit, Automatic and IndexingMode Assert.isTrue(personInfo.getContainerName().equals(NoDBAnnotationPerson.class.getSimpleName()), "should be default collection name"); - Assert.isTrue(policy.automatic() == TestConstants.DEFAULT_INDEXINGPOLICY_AUTOMATIC, + Assert.isTrue(policy.isAutomatic() == TestConstants.DEFAULT_INDEXING_POLICY_AUTOMATIC, "should be default indexing policy automatic"); - Assert.isTrue(policy.indexingMode() == TestConstants.DEFAULT_INDEXINGPOLICY_MODE, + Assert.isTrue(policy.getIndexingMode() == TestConstants.DEFAULT_INDEXING_POLICY_MODE, "should be default indexing policy mode"); // IncludedPaths and ExcludedPaths @@ -50,8 +49,8 @@ public void testDefaultIndexingPolicyAnnotation() { // and the paths of policy will never be set from azure service. // testIndexingPolicyPathsEquals(policy.getIncludedPaths(), TestConstants.DEFAULT_INCLUDEDPATHS); // testIndexingPolicyPathsEquals(policy.getExcludedPaths(), TestConstants.DEFAULT_EXCLUDEDPATHS); - Assert.isTrue(policy.includedPaths().isEmpty(), "default includedpaths size must be 0"); - Assert.isTrue(policy.excludedPaths().isEmpty(), "default excludedpaths size must be 0"); + Assert.isTrue(policy.getIncludedPaths().isEmpty(), "default includedpaths size must be 0"); + Assert.isTrue(policy.getExcludedPaths().isEmpty(), "default excludedpaths size must be 0"); } @Test @@ -67,14 +66,14 @@ public void testIndexingPolicyAnnotation() { Assert.isTrue(roleInfo.getContainerName().equals(TestConstants.ROLE_COLLECTION_NAME), "should be Role(class) collection name"); - Assert.isTrue(policy.automatic() == TestConstants.INDEXINGPOLICY_AUTOMATIC, + Assert.isTrue(policy.isAutomatic() == TestConstants.INDEXING_POLICY_AUTOMATIC, "should be Role(class) indexing policy automatic"); - Assert.isTrue(policy.indexingMode() == TestConstants.INDEXINGPOLICY_MODE, + Assert.isTrue(policy.getIndexingMode() == TestConstants.INDEXING_POLICY_MODE, "should be Role(class) indexing policy mode"); // IncludedPaths and ExcludedPaths - TestUtils.testIndexingPolicyPathsEquals(policy.includedPaths(), TestConstants.INCLUDEDPATHS); - TestUtils.testIndexingPolicyPathsEquals(policy.excludedPaths(), TestConstants.EXCLUDEDPATHS); +// TestUtils.testIndexingPolicyPathsEquals(policy.getIncludedPaths(), TestConstants.INCLUDED_PATHS); +// TestUtils.testIndexingPolicyPathsEquals(policy.getExcludedPaths(), TestConstants.EXCLUDED_PATHS); } @Test diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/SimpleCosmosRepositoryIllegalTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/SimpleCosmosRepositoryIllegalTest.java index 39291c39e1cd..044efdfbbc89 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/SimpleCosmosRepositoryIllegalTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/SimpleCosmosRepositoryIllegalTest.java @@ -3,9 +3,9 @@ package com.azure.spring.data.cosmos.repository; import com.azure.spring.data.cosmos.core.CosmosOperations; +import com.azure.spring.data.cosmos.domain.Person; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.repository.support.SimpleCosmosRepository; -import com.azure.spring.data.cosmos.domain.Person; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/SimpleCosmosRepositoryUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/SimpleCosmosRepositoryUnitTest.java index 80cb570fe988..b59dce650977 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/SimpleCosmosRepositoryUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/SimpleCosmosRepositoryUnitTest.java @@ -3,12 +3,12 @@ package com.azure.spring.data.cosmos.repository; -import com.azure.spring.data.cosmos.core.CosmosOperations; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import com.azure.spring.data.cosmos.repository.support.SimpleCosmosRepository; import com.azure.spring.data.cosmos.common.TestConstants; +import com.azure.spring.data.cosmos.core.CosmosOperations; import com.azure.spring.data.cosmos.domain.Address; import com.azure.spring.data.cosmos.domain.Person; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; +import com.azure.spring.data.cosmos.repository.support.SimpleCosmosRepository; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Rule; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/TestRepositoryConfig.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/TestRepositoryConfig.java index 2556f379aa8e..d4289436ee61 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/TestRepositoryConfig.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/TestRepositoryConfig.java @@ -2,15 +2,14 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository; -import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.spring.data.cosmos.common.DynamicContainer; +import com.azure.spring.data.cosmos.common.ResponseDiagnosticsTestUtils; +import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories; import com.azure.spring.data.cosmos.repository.config.EnableReactiveCosmosRepositories; -import com.azure.spring.data.cosmos.common.DynamicContainer; -import com.azure.spring.data.cosmos.common.ResponseDiagnosticsTestUtils; -import com.azure.spring.data.cosmos.common.TestConstants; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -18,7 +17,7 @@ import org.springframework.util.StringUtils; @Configuration -@PropertySource(value = {"classpath:application.properties"}) +@PropertySource(value = { "classpath:application.properties" }) @EnableCosmosRepositories @EnableReactiveCosmosRepositories public class TestRepositoryConfig extends AbstractCosmosConfiguration { @@ -28,24 +27,11 @@ public class TestRepositoryConfig extends AbstractCosmosConfiguration { @Value("${cosmosdb.key:}") private String cosmosDbKey; - @Value("${cosmosdb.connection-string:}") - private String connectionString; - @Value("${cosmosdb.database:}") private String database; - @Value("${cosmosdb.populateQueryMetrics}") - private boolean populateQueryMetrics; - - private RequestOptions getRequestOptions() { - final RequestOptions options = new RequestOptions(); - - options.setConsistencyLevel(ConsistencyLevel.SESSION); -// options.setDisableRUPerMinuteUsage(true); - options.setScriptLoggingEnabled(true); - - return options; - } + @Value("${cosmosdb.queryMetricsEnabled}") + private boolean queryMetricsEnabled; @Bean public ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils() { @@ -54,20 +40,17 @@ public ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils() { @Bean public CosmosDBConfig getConfig() { - final String dbName = StringUtils.hasText(this.database) ? this.database : TestConstants.DB_NAME; - final RequestOptions options = getRequestOptions(); - final CosmosDBConfig.CosmosDBConfigBuilder builder; - - if (StringUtils.hasText(this.cosmosDbUri) - && StringUtils.hasText(this.cosmosDbKey)) { - builder = CosmosDBConfig.builder(cosmosDbUri, cosmosDbKey, dbName); - } else { - builder = CosmosDBConfig.builder(connectionString, dbName); - } - return builder.requestOptions(options) - .populateQueryMetrics(populateQueryMetrics) - .responseDiagnosticsProcessor(responseDiagnosticsTestUtils().getResponseDiagnosticsProcessor()) - .build(); + final String dbName = StringUtils.hasText(this.database) ? this.database : + TestConstants.DB_NAME; + return CosmosDBConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .key(cosmosDbKey) + .endpoint(cosmosDbUri) + .contentResponseOnWriteEnabled(true)) + .database(dbName) + .enableQueryMetrics(queryMetricsEnabled) + .responseDiagnosticsProcessor(responseDiagnosticsTestUtils().getResponseDiagnosticsProcessor()) + .build(); } @Bean diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/AddressRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/AddressRepositoryIT.java index 0a78bfebcbe8..024d38ad5e91 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/AddressRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/AddressRepositoryIT.java @@ -2,16 +2,21 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.data.cosmos.PartitionKey; -import com.azure.spring.data.cosmos.core.CosmosTemplate; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.common.TestUtils; +import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.domain.Address; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.AddressRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.assertj.core.util.Lists; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ContactRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ContactRepositoryIT.java index bbcb0aedadfc..7c256d9a8e03 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ContactRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ContactRepositoryIT.java @@ -2,14 +2,19 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.spring.data.cosmos.core.CosmosTemplate; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.common.TestUtils; +import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.domain.Contact; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.ContactRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.assertj.core.util.Lists; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CosmosAnnotationIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CosmosAnnotationIT.java index 7c5253e0c118..f408825467ff 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CosmosAnnotationIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CosmosAnnotationIT.java @@ -2,19 +2,19 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.data.cosmos.CosmosContainerProperties; -import com.azure.data.cosmos.IndexingPolicy; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.IndexingPolicy; +import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.common.TestConstants; +import com.azure.spring.data.cosmos.common.TestUtils; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.common.TestUtils; import com.azure.spring.data.cosmos.domain.Role; import com.azure.spring.data.cosmos.domain.TimeToLiveSample; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.junit.AfterClass; import org.junit.Before; import org.junit.Ignore; @@ -52,7 +52,7 @@ public class CosmosAnnotationIT { @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - final CosmosDbFactory cosmosDbFactory = new CosmosDbFactory(dbConfig); + final CosmosDBFactory cosmosDbFactory = new CosmosDBFactory(dbConfig); roleInfo = new CosmosEntityInformation<>(Role.class); sampleInfo = new CosmosEntityInformation<>(TimeToLiveSample.class); @@ -81,24 +81,24 @@ public static void afterClassCleanup() { @Test public void testTimeToLiveAnnotation() { Integer timeToLive = sampleInfo.getTimeToLive(); - assertThat(timeToLive).isEqualTo(collectionSample.defaultTimeToLive()); + assertThat(timeToLive).isEqualTo(collectionSample.getDefaultTimeToLiveInSeconds()); timeToLive = roleInfo.getTimeToLive(); - assertThat(timeToLive).isEqualTo(collectionRole.defaultTimeToLive()); + assertThat(timeToLive).isEqualTo(collectionRole.getDefaultTimeToLiveInSeconds()); } @Test @Ignore // TODO(kuthapar): Ignore this test case for now, will update this from service update. public void testIndexingPolicyAnnotation() { - final IndexingPolicy policy = collectionRole.indexingPolicy(); + final IndexingPolicy policy = collectionRole.getIndexingPolicy(); - Assert.isTrue(policy.indexingMode() == TestConstants.INDEXINGPOLICY_MODE, + Assert.isTrue(policy.getIndexingMode() == TestConstants.INDEXING_POLICY_MODE, "unmatched collection policy indexing mode of class Role"); - Assert.isTrue(policy.automatic() == TestConstants.INDEXINGPOLICY_AUTOMATIC, + Assert.isTrue(policy.isAutomatic() == TestConstants.INDEXING_POLICY_AUTOMATIC, "unmatched collection policy automatic of class Role"); - TestUtils.testIndexingPolicyPathsEquals(policy.includedPaths(), TestConstants.INCLUDEDPATHS); - TestUtils.testIndexingPolicyPathsEquals(policy.excludedPaths(), TestConstants.EXCLUDEDPATHS); + TestUtils.testIndexingPolicyPathsEquals(policy.getIncludedPaths(), TestConstants.INCLUDED_PATHS); + TestUtils.testIndexingPolicyPathsEquals(policy.getExcludedPaths(), TestConstants.EXCLUDED_PATHS); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CustomerRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CustomerRepositoryIT.java index 5b2eb1866a5e..a910b94adb38 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CustomerRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CustomerRepositoryIT.java @@ -3,11 +3,15 @@ package com.azure.spring.data.cosmos.repository.integration; import com.azure.spring.data.cosmos.core.CosmosTemplate; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.domain.Customer; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.CustomerRepository; -import org.junit.*; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.NonNull; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/IntegerIdDomainRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/IntegerIdDomainRepositoryIT.java index ec95314fb903..fe786a4d2054 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/IntegerIdDomainRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/IntegerIdDomainRepositoryIT.java @@ -4,12 +4,17 @@ import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.domain.IntegerIdDomain; +import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.IntegerIdDomainRepository; -import org.junit.*; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; @@ -17,7 +22,12 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.*; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/MemoRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/MemoRepositoryIT.java index 11e0a8a504dd..e8919bcea0ea 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/MemoRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/MemoRepositoryIT.java @@ -2,16 +2,22 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.spring.data.cosmos.core.CosmosTemplate; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.common.TestUtils; +import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.domain.Importance; import com.azure.spring.data.cosmos.domain.Memo; +import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.MemoRepository; -import org.junit.*; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java index dee802834c9a..18f096b88f0f 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java @@ -2,19 +2,18 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedResponse; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.FeedResponse; +import com.azure.spring.data.cosmos.common.TestConstants; +import com.azure.spring.data.cosmos.common.TestUtils; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.common.TestUtils; import com.azure.spring.data.cosmos.domain.PageableAddress; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.PageableAddressRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -166,22 +165,22 @@ public void testFindWithoutPartitionKeyMultiPages() { public void testOffsetAndLimit() { final int skipCount = 2; final int takeCount = 2; - final List results = new ArrayList<>(); - final FeedOptions options = new FeedOptions(); - options.enableCrossPartitionQuery(true); - options.maxDegreeOfParallelism(2); + final List results = new ArrayList<>(); + final CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); + options.setMaxDegreeOfParallelism(2); final String query = "SELECT * from c OFFSET " + skipCount + " LIMIT " + takeCount; - final CosmosClient cosmosClient = applicationContext.getBean(CosmosClient.class); - final Flux> feedResponseFlux = + final CosmosAsyncClient cosmosClient = applicationContext.getBean(CosmosAsyncClient.class); + final Flux> feedResponseFlux = cosmosClient.getDatabase(dbConfig.getDatabase()) .getContainer(entityInformation.getContainerName()) - .queryItems(query, options); + .queryItems(query, options, PageableAddress.class) + .byPage(); StepVerifier.create(feedResponseFlux) .consumeNextWith(cosmosItemPropertiesFeedResponse -> - results.addAll(cosmosItemPropertiesFeedResponse.results())) + results.addAll(cosmosItemPropertiesFeedResponse.getResults())) .verifyComplete(); assertThat(results.size()).isEqualTo(takeCount); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableMemoRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableMemoRepositoryIT.java index a941af82390b..528cf0ab0445 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableMemoRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableMemoRepositoryIT.java @@ -2,18 +2,17 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedResponse; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.FeedResponse; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.domain.Importance; import com.azure.spring.data.cosmos.domain.PageableMemo; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.PageableMemoRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; @@ -27,7 +26,13 @@ import reactor.core.publisher.Flux; import reactor.test.StepVerifier; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -126,26 +131,26 @@ public void testOffsetAndLimitGreaterThanTotal() { verifyItemsWithOffsetAndLimit(skipCount, takeCount, TOTAL_CONTENT_SIZE - skipCount); } - private Flux> getItemsWithOffsetAndLimit(int skipCount, int takeCount) { - final FeedOptions options = new FeedOptions(); - options.enableCrossPartitionQuery(true); - options.maxDegreeOfParallelism(2); + private Flux> getItemsWithOffsetAndLimit(int skipCount, int takeCount) { + final CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); + options.setMaxDegreeOfParallelism(2); final String query = "SELECT * from c OFFSET " + skipCount + " LIMIT " + takeCount; - final CosmosClient cosmosClient = applicationContext.getBean(CosmosClient.class); + final CosmosAsyncClient cosmosClient = applicationContext.getBean(CosmosAsyncClient.class); return cosmosClient.getDatabase(dbConfig.getDatabase()) - .getContainer(entityInformation.getContainerName()) - .queryItems(query, options); + .getContainer(entityInformation.getContainerName()) + .queryItems(query, options, PageableMemo.class) + .byPage(); } private void verifyItemsWithOffsetAndLimit(int skipCount, int takeCount, int verifyCount) { - final List itemsWithOffsetAndLimit = new ArrayList<>(); - final Flux> itemsWithOffsetAndLimitFlux = + final List itemsWithOffsetAndLimit = new ArrayList<>(); + final Flux> itemsWithOffsetAndLimitFlux = getItemsWithOffsetAndLimit(skipCount, takeCount); StepVerifier.create(itemsWithOffsetAndLimitFlux) .thenConsumeWhile(cosmosItemPropertiesFeedResponse -> { - itemsWithOffsetAndLimit.addAll(cosmosItemPropertiesFeedResponse.results()); + itemsWithOffsetAndLimit.addAll(cosmosItemPropertiesFeedResponse.getResults()); return true; }) .verifyComplete(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageablePersonRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageablePersonRepositoryIT.java index 20cc38a9ce36..a7f06d1a5b19 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageablePersonRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageablePersonRepositoryIT.java @@ -4,12 +4,11 @@ import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.domain.Address; import com.azure.spring.data.cosmos.domain.PageablePerson; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.PageablePersonRepository; -import org.apache.commons.io.FileUtils; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.apache.commons.lang3.StringUtils; import org.junit.AfterClass; import org.junit.Before; @@ -21,7 +20,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -30,6 +33,7 @@ public class PageablePersonRepositoryIT { private static final int TOTAL_CONTENT_SIZE = 50; + public static final long ONE_KB = 1024L; private static final CosmosEntityInformation entityInformation = new CosmosEntityInformation<>(PageablePerson.class); @@ -59,7 +63,7 @@ public void setUp() { for (int i = 0; i < TOTAL_CONTENT_SIZE; i++) { final List hobbies = new ArrayList<>(); hobbies.add(StringUtils.repeat("hobbies-" + UUID.randomUUID().toString(), - (int) FileUtils.ONE_KB * 10)); + (int) ONE_KB * 10)); final List
address = new ArrayList<>(); address.add(new Address("postalCode-" + UUID.randomUUID().toString(), "street-" + UUID.randomUUID().toString(), diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositoryIT.java index 3910aa2a3be1..eeececf58d12 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositoryIT.java @@ -2,21 +2,29 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.core.CosmosTemplate; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import com.google.common.collect.Lists; import com.azure.spring.data.cosmos.domain.Project; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.ProjectRepository; -import org.junit.*; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.NonNull; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @@ -497,7 +505,10 @@ public void testFindAllByPartitionKey() { repository.findAll(new PartitionKey(CREATOR_0)); // Since there are two projects with creator_0 assertThat(findAll.size()).isEqualTo(2); - assertThat(findAll.containsAll(Lists.newArrayList(PROJECT_0, PROJECT_4))).isTrue(); + List projectList = new ArrayList<>(); + projectList.add(PROJECT_0); + projectList.add(PROJECT_4); + assertThat(findAll.containsAll(projectList)).isTrue(); findAll = repository.findAll(new PartitionKey(CREATOR_1)); // Since there is one projects with creator_1 diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositorySortIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositorySortIT.java index 0402c2c9e8c7..fc05c600c160 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositorySortIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositorySortIT.java @@ -4,13 +4,17 @@ import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.domain.SortedProject; +import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.SortedProjectRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.assertj.core.util.Lists; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/QuestionRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/QuestionRepositoryIT.java index 5410ca9f445e..5cd17d70a034 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/QuestionRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/QuestionRepositoryIT.java @@ -3,13 +3,16 @@ package com.azure.spring.data.cosmos.repository.integration; import com.azure.spring.data.cosmos.core.CosmosTemplate; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.domain.Question; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; -import com.azure.spring.data.cosmos.repository.repository.ProjectRepository; import com.azure.spring.data.cosmos.repository.repository.QuestionRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.assertj.core.util.Lists; -import org.junit.*; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; @@ -41,9 +44,6 @@ public class QuestionRepositoryIT { @Autowired private QuestionRepository repository; - @Autowired - private ProjectRepository projectRepository; - @Before public void setUp() { if (!isSetupDone) { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveCourseRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveCourseRepositoryIT.java index df2780cfc216..9e7e17f35271 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveCourseRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveCourseRepositoryIT.java @@ -2,13 +2,13 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.data.cosmos.PartitionKey; +import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.core.ReactiveCosmosTemplate; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.domain.Course; +import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.ReactiveCourseRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosDBAnnotationIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosDBAnnotationIT.java index 608e26b6b60b..02ec72cb3d2c 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosDBAnnotationIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosDBAnnotationIT.java @@ -2,18 +2,19 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.spring.data.cosmos.CosmosDbFactory; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.config.CosmosDBConfig; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.convert.ObjectMapperFactory; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.domain.SpELBeanStudent; import com.azure.spring.data.cosmos.domain.SpELPropertyStudent; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; @@ -83,8 +84,13 @@ public void testDynamicContainerNameWithBeanExpression() { @Test public void testDatabaseOperationsOnDynamicallyNamedCollection() throws ClassNotFoundException { - final CosmosDBConfig dbConfig = CosmosDBConfig.builder(dbUri, dbKey, TestConstants.DB_NAME).build(); - final CosmosDbFactory dbFactory = new CosmosDbFactory(dbConfig); + final CosmosDBConfig dbConfig = CosmosDBConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(dbUri) + .key(dbKey)) + .database(TestConstants.DB_NAME) + .build(); + final CosmosDBFactory dbFactory = new CosmosDBFactory(dbConfig); cosmosEntityInformation = new CosmosEntityInformation<>(SpELPropertyStudent.class); final CosmosMappingContext dbContext = new CosmosMappingContext(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SquareRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SquareRepositoryIT.java index f7a0bbbc9a5c..131fe0c75626 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SquareRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SquareRepositoryIT.java @@ -2,12 +2,12 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.integration; -import com.azure.spring.data.cosmos.core.CosmosTemplate; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.common.TestUtils; +import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.domain.inheritance.Square; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.SquareRepository; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/StudentRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/StudentRepositoryIT.java index 5da443d21f66..fc8a1ef6cb4b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/StudentRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/StudentRepositoryIT.java @@ -3,11 +3,15 @@ package com.azure.spring.data.cosmos.repository.integration; import com.azure.spring.data.cosmos.core.CosmosTemplate; -import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.azure.spring.data.cosmos.domain.Student; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.StudentRepository; -import org.junit.*; +import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/AddressRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/AddressRepository.java index 69cb5ee06e9e..8b7fed466932 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/AddressRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/AddressRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.Address; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; import java.util.List; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ContactRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ContactRepository.java index e13047d28442..1b3da03888f0 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ContactRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ContactRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.Contact; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; import java.util.List; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/CustomerRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/CustomerRepository.java index 6a15bd90b4fa..ed015518d9bd 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/CustomerRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/CustomerRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.Customer; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import java.util.List; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/IntegerIdDomainRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/IntegerIdDomainRepository.java index 295d7f3d7c66..eb064a5f9478 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/IntegerIdDomainRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/IntegerIdDomainRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.IntegerIdDomain; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; @Repository diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/MemoRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/MemoRepository.java index 56f51bef2f60..1c7bbbe057aa 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/MemoRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/MemoRepository.java @@ -2,9 +2,9 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.Importance; import com.azure.spring.data.cosmos.domain.Memo; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; import java.util.Date; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/PartitionPersonRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/PartitionPersonRepository.java index df1a33f88ae1..1fefb26bbc72 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/PartitionPersonRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/PartitionPersonRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.PartitionPerson; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; @Repository diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/PersonRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/PersonRepository.java index 11c63be3e4af..e305178f6b75 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/PersonRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/PersonRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.Person; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; @Repository diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ProjectRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ProjectRepository.java index c930ca9d8486..562dab56f24a 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ProjectRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ProjectRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.Project; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/QuestionRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/QuestionRepository.java index 0d043875c128..f45d4621ec9e 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/QuestionRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/QuestionRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.Question; +import com.azure.spring.data.cosmos.repository.CosmosRepository; public interface QuestionRepository extends CosmosRepository { } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ReactiveCourseRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ReactiveCourseRepository.java index 50f589f4b31e..8acdf9641d31 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ReactiveCourseRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/ReactiveCourseRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.ReactiveCosmosRepository; import com.azure.spring.data.cosmos.domain.Course; +import com.azure.spring.data.cosmos.repository.ReactiveCosmosRepository; import reactor.core.publisher.Flux; import java.util.Collection; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SortedProjectRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SortedProjectRepository.java index e841aaab8d2c..0bdd871e184b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SortedProjectRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SortedProjectRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.SortedProject; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SquareRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SquareRepository.java index 0026cc7b8ad1..a46748b0c523 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SquareRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SquareRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.inheritance.Square; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; @Repository diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/StudentRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/StudentRepository.java index f8039bc21388..d47f7f0a6c28 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/StudentRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/StudentRepository.java @@ -2,8 +2,8 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.repository; -import com.azure.spring.data.cosmos.repository.CosmosRepository; import com.azure.spring.data.cosmos.domain.Student; +import com.azure.spring.data.cosmos.repository.CosmosRepository; import org.springframework.stereotype.Repository; import java.util.List; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/support/CosmosEntityInformationUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/support/CosmosEntityInformationUnitTest.java index 3a5ecd362fe3..d7492ae1a621 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/support/CosmosEntityInformationUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/support/CosmosEntityInformationUnitTest.java @@ -2,9 +2,9 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.support; +import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; -import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.domain.Address; import com.azure.spring.data.cosmos.domain.Person; import com.azure.spring.data.cosmos.domain.Student; @@ -124,7 +124,7 @@ public void testNonVersionedEntity() { assertThat(isVersioned).isFalse(); } - @Document(collection = "testCollection") + @Document(container = "testContainer") private static class Volunteer { String id; String name; @@ -176,7 +176,7 @@ public void setName(String name) { } } - @Document(collection = "testCollection") + @Document(container = "testContainer") private static class VersionedVolunteer { private String id; private String name; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/support/CosmosRepositoryFactoryBeanUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/support/CosmosRepositoryFactoryBeanUnitTest.java index cb205d625cc9..d7c2c127ef50 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/support/CosmosRepositoryFactoryBeanUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/support/CosmosRepositoryFactoryBeanUnitTest.java @@ -2,21 +2,16 @@ // Licensed under the MIT License. package com.azure.spring.data.cosmos.repository.support; -import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.repository.repository.PersonRepository; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.repository.core.support.RepositoryFactorySupport; import static org.assertj.core.api.Assertions.assertThat; -@SuppressWarnings("unchecked") @RunWith(MockitoJUnitRunner.class) public class CosmosRepositoryFactoryBeanUnitTest { - @Mock - CosmosTemplate dbTemplate; @Test public void testCreateRepositoryFactory() { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/resources/application.properties b/sdk/cosmos/azure-spring-data-cosmos/src/test/resources/application.properties index 12b7c8f46f80..37e5a71beb70 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/resources/application.properties +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/resources/application.properties @@ -2,9 +2,6 @@ cosmosdb.uri=${ACCOUNT_HOST} cosmosdb.key=${ACCOUNT_KEY} cosmosdb.secondaryKey=${SECONDARY_ACCOUNT_KEY} -#You can also use connection string instead of uri and key to connect to cosmos DB -#cosmosdb.connection-string=${DOCUMENTDB_CONNECTION_STRING} - dynamic.collection.name=spel-property-collection # Performance test configurations perf.recursive.times=10 @@ -12,4 +9,4 @@ perf.batch.size=3 perf.acceptance.percentage=10 # Populate query metrics -cosmosdb.populateQueryMetrics=true +cosmosdb.queryMetricsEnabled=true From e7bc7063e7e69c413c72985956caf13994d94f58 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Wed, 15 Jul 2020 22:20:10 -0700 Subject: [PATCH 2/6] Updated CosmosDbUtils name --- .../data/cosmos/common/CosmosDBUtils.java | 85 ------------------- .../data/cosmos/common/CosmosDbUtils.java | 4 +- .../data/cosmos/core/CosmosTemplate.java | 28 +++--- .../cosmos/core/ReactiveCosmosTemplate.java | 28 +++--- 4 files changed, 30 insertions(+), 115 deletions(-) delete mode 100644 sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDBUtils.java diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDBUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDBUtils.java deleted file mode 100644 index 6e0e052d8025..000000000000 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDBUtils.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.spring.data.cosmos.common; - -import com.azure.data.cosmos.CosmosResponse; -import com.azure.data.cosmos.CosmosResponseDiagnostics; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.FeedResponseDiagnostics; -import com.azure.data.cosmos.Resource; -import com.azure.spring.data.cosmos.core.convert.ObjectMapperFactory; -import com.azure.spring.data.cosmos.exception.ConfigurationException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.azure.spring.data.cosmos.core.ResponseDiagnostics; -import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.lang.NonNull; - -import java.io.IOException; - -/** - * Util class to fill and process response diagnostics - */ -public class CosmosdbUtils { - - private static final Logger LOGGER = LoggerFactory.getLogger(CosmosdbUtils.class); - - /** - * Get a copy of an existing instance - * @param instance the known instance - * @param type of instance - * @return copy instance - * @throws ConfigurationException if the class type is invalid - */ - @SuppressWarnings("unchecked") - public static T getCopyFrom(@NonNull T instance) { - final ObjectMapper mapper = ObjectMapperFactory.getObjectMapper(); - - try { - final String s = mapper.writeValueAsString(instance); - return (T) mapper.readValue(s, instance.getClass()); - } catch (IOException e) { - throw new ConfigurationException("failed to get copy from " - + instance.getClass().getName(), e); - } - } - - /** - * Generate ResponseDiagnostics with cosmos and feed response diagnostics - * - * @param type of cosmosResponse - * @param responseDiagnosticsProcessor collect Response Diagnostics from API responses and - * then set in {@link ResponseDiagnostics} object. - * @param cosmosResponse response from cosmos - * @param feedResponse response from feed - */ - public static void fillAndProcessResponseDiagnostics( - ResponseDiagnosticsProcessor responseDiagnosticsProcessor, - CosmosResponse cosmosResponse, FeedResponse feedResponse) { - if (responseDiagnosticsProcessor == null) { - return; - } - CosmosResponseDiagnostics cosmosResponseDiagnostics = null; - if (cosmosResponse != null) { - cosmosResponseDiagnostics = cosmosResponse.cosmosResponseDiagnosticsString(); - } - FeedResponseDiagnostics feedResponseDiagnostics = null; - ResponseDiagnostics.CosmosResponseStatistics cosmosResponseStatistics = null; - if (feedResponse != null) { - feedResponseDiagnostics = feedResponse.feedResponseDiagnostics(); - cosmosResponseStatistics = new ResponseDiagnostics.CosmosResponseStatistics(feedResponse); - } - if (cosmosResponseDiagnostics == null - && (feedResponseDiagnostics == null || feedResponseDiagnostics.toString().isEmpty()) - && cosmosResponseStatistics == null) { - LOGGER.debug("Empty response diagnostics"); - return; - } - final ResponseDiagnostics responseDiagnostics = - new ResponseDiagnostics(cosmosResponseDiagnostics, feedResponseDiagnostics, cosmosResponseStatistics); - - // Process response diagnostics - responseDiagnosticsProcessor.processResponseDiagnostics(responseDiagnostics); - } -} diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java index 818b683ff9b8..bf9e10e65586 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java @@ -12,9 +12,9 @@ /** * Util class to fill and process response diagnostics */ -public class CosmosDBUtils { +public class CosmosDbUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(CosmosDBUtils.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CosmosDbUtils.class); /** * Generate ResponseDiagnostics with cosmos and feed response diagnostics diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java index 425000bf9436..2ca5f2b75163 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java @@ -16,7 +16,7 @@ import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.models.ThroughputProperties; import com.azure.spring.data.cosmos.CosmosDBFactory; -import com.azure.spring.data.cosmos.common.CosmosDBUtils; +import com.azure.spring.data.cosmos.common.CosmosDbUtils; import com.azure.spring.data.cosmos.common.Memoizer; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.generator.CountQueryGenerator; @@ -140,7 +140,7 @@ public T insert(String containerName, T objectToSave, PartitionKey partition .getContainer(containerName) .createItem(originalItem, partitionKey, options) .doOnNext(cosmosItemResponse -> - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to insert item", throwable)) @@ -176,7 +176,7 @@ public T findById(Object id, Class domainType, PartitionKey partitionKey) .getContainer(containerName) .readItem(id.toString(), partitionKey, JsonNode.class) .flatMap(cosmosItemResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.justOrEmpty(toDomainObject(domainType, cosmosItemResponse.getItem())); }) @@ -210,7 +210,7 @@ public T findById(String containerName, Object id, Class domainType) { .queryItems(query, options, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Mono.justOrEmpty(cosmosItemFeedResponse .getResults() @@ -273,7 +273,7 @@ public T upsertAndReturnEntity(String containerName, T object) { .getDatabase(this.databaseName) .getContainer(containerName) .upsertItem(originalItem, options) - .doOnNext(response -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + .doOnNext(response -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, response.getDiagnostics(), null)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to upsert" + " item", throwable)) @@ -334,7 +334,7 @@ public List findAll(PartitionKey partitionKey, final Class domainType) .queryItems("SELECT * FROM r", cosmosQueryRequestOptions, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, cosmosItemFeedResponse); return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) @@ -367,7 +367,7 @@ public void deleteContainer(@NonNull String containerName) { .getContainer(containerName) .delete() .doOnNext(response -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, response.getDiagnostics(), null); }) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to delete " + @@ -390,7 +390,7 @@ public CosmosContainerProperties createContainerIfNotExists(CosmosEntityInformat .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to create database", throwable)) .flatMap(cosmosDatabaseResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosDatabaseResponse.getDiagnostics(), null); final CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties( @@ -419,7 +419,7 @@ public CosmosContainerProperties createContainerIfNotExists(CosmosEntityInformat CosmosDBExceptionUtils.exceptionHandler("Failed to create container", throwable)) .doOnNext(cosmosContainerResponse -> - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosContainerResponse.getDiagnostics(), null)); }) .block(); @@ -449,7 +449,7 @@ public void deleteById(String containerName, Object id, PartitionKey partitionKe cosmosAsyncClient.getDatabase(this.databaseName) .getContainer(containerName) .deleteItem(id.toString(), partitionKey) - .doOnNext(response -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + .doOnNext(response -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, response.getDiagnostics(), null)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", @@ -569,7 +569,7 @@ public Page paginationQuery(DocumentQuery query, Class domainType, final FeedResponse feedResponse = feedResponseFlux .doOnNext(propertiesFeedResponse -> - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, propertiesFeedResponse.getCosmosDiagnostics(), propertiesFeedResponse)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to query items", throwable)) @@ -650,7 +650,7 @@ private Long getCountValue(DocumentQuery query, String containerName) { return executeQuery(querySpec, containerName, options) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to get count value", throwable)) - .doOnNext(response -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + .doOnNext(response -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, response)) .next() .map(r -> r.getResults().get(0).asLong()) @@ -698,7 +698,7 @@ private List findItems(@NonNull DocumentQuery query, .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) @@ -732,7 +732,7 @@ private T deleteItem(@NonNull JsonNode jsonNode, .getDatabase(this.databaseName) .getContainer(containerName) .deleteItem(jsonNode.get("id").asText(), partitionKey) - .doOnNext(response -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + .doOnNext(response -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, response.getDiagnostics(), null)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", throwable)) diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java index fef7e40ec9a6..c12b9859b3ca 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java @@ -14,7 +14,7 @@ import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.models.ThroughputProperties; import com.azure.spring.data.cosmos.CosmosDBFactory; -import com.azure.spring.data.cosmos.common.CosmosDBUtils; +import com.azure.spring.data.cosmos.common.CosmosDbUtils; import com.azure.spring.data.cosmos.common.Memoizer; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.generator.CountQueryGenerator; @@ -99,7 +99,7 @@ public Mono createContainerIfNotExists(CosmosEntityInfo .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to create database", throwable)) .flatMap(cosmosDatabaseResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosDatabaseResponse.getDiagnostics(), null); final CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties( @@ -125,7 +125,7 @@ public Mono createContainerIfNotExists(CosmosEntityInfo return cosmosContainerResponseMono .map(cosmosContainerResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosContainerResponse.getDiagnostics(), null); return cosmosContainerResponse; }) @@ -178,7 +178,7 @@ public Flux findAll(PartitionKey partitionKey, Class domainType) { .queryItems("SELECT * FROM r", cosmosQueryRequestOptions, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) @@ -225,7 +225,7 @@ public Mono findById(String containerName, Object id, Class domainType .queryItems(query, options, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Mono.justOrEmpty(cosmosItemFeedResponse @@ -258,7 +258,7 @@ public Mono findById(Object id, Class domainType, PartitionKey partiti .getContainer(containerName) .readItem(id.toString(), partitionKey, JsonNode.class) .flatMap(cosmosItemResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.justOrEmpty(toDomainObject(domainType, cosmosItemResponse.getItem())); @@ -302,7 +302,7 @@ public Mono insert(T objectToSave) { CosmosDBExceptionUtils.exceptionHandler("Failed to insert " + "item", throwable)) .flatMap(cosmosItemResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.just(toDomainObject(domainType, cosmosItemResponse.getItem())); @@ -338,7 +338,7 @@ public Mono insert(String containerName, Object objectToSave, CosmosDBExceptionUtils.exceptionHandler("Failed to insert " + "item", throwable)) .flatMap(cosmosItemResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.just(toDomainObject(domainType, cosmosItemResponse.getItem())); @@ -376,7 +376,7 @@ public Mono upsert(String containerName, T object) { .getContainer(containerName) .upsertItem(originalItem, options) .flatMap(cosmosItemResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.just(toDomainObject(domainType, cosmosItemResponse.getItem())); @@ -408,7 +408,7 @@ public Mono deleteById(String containerName, Object id, PartitionKey parti .getContainer(containerName) .deleteItem(id.toString(), partitionKey) .doOnNext(cosmosItemResponse -> - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to delete " + @@ -530,7 +530,7 @@ private Mono getCountValue(DocumentQuery query, String containerName) { options.setQueryMetricsEnabled(isPopulateQueryMetrics); return executeQuery(querySpec, containerName, options) - .doOnNext(feedResponse -> CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + .doOnNext(feedResponse -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, feedResponse)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to get count value", throwable)) @@ -563,7 +563,7 @@ public void deleteContainer(@NonNull String containerName) { .getContainer(containerName) .delete() .doOnNext(cosmosContainerResponse -> - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosContainerResponse.getDiagnostics(), null)) .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to delete container" @@ -593,7 +593,7 @@ private Flux findItems(@NonNull DocumentQuery query, .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, cosmosItemFeedResponse); return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) @@ -638,7 +638,7 @@ private Mono deleteItem(@NonNull JsonNode jsonNode, .getContainer(containerName) .deleteItem(jsonNode.get("id").asText(), partitionKey) .map(cosmosItemResponse -> { - CosmosDBUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return cosmosItemResponse; }) From f660fb009fe4a91616e6c9b5bb58c36e13692de5 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 16 Jul 2020 11:30:43 -0700 Subject: [PATCH 3/6] Updated CosmosDB* CosmosDb* to Cosmos* class names for rebranding --- sdk/cosmos/azure-spring-data-cosmos/README.md | 30 +-- sdk/cosmos/azure-spring-data-cosmos/pom.xml | 2 - .../azure/spring/data/cosmos/Constants.java | 4 +- ...osmosDBFactory.java => CosmosFactory.java} | 36 ++-- .../{CosmosDbUtils.java => CosmosUtils.java} | 14 +- .../config/AbstractCosmosConfiguration.java | 45 +++-- ...{CosmosDBConfig.java => CosmosConfig.java} | 76 ++++---- .../data/cosmos/core/CosmosTemplate.java | 182 +++++++++--------- .../cosmos/core/ReactiveCosmosTemplate.java | 153 +++++++-------- .../data/cosmos/core/ResponseDiagnostics.java | 4 +- .../core/convert/MappingCosmosConverter.java | 17 +- ...eption.java => CosmosAccessException.java} | 10 +- ...onUtils.java => CosmosExceptionUtils.java} | 6 +- .../support/SimpleCosmosRepository.java | 12 +- .../com/azure/cosmos/AppConfiguration.java | 26 +-- .../cosmos/AppConfigurationCodeSnippet.java | 24 +-- ...BProperties.java => CosmosProperties.java} | 4 +- .../cosmos/UserRepositoryConfiguration.java | 20 +- ...ryTestIT.java => CosmosFactoryTestIT.java} | 24 +-- .../config/AbstractCosmosConfigurationIT.java | 56 +++--- .../data/cosmos/core/CosmosTemplateIT.java | 16 +- .../core/CosmosTemplatePartitionIT.java | 10 +- .../cosmos/core/CosmosTemplateUnitTest.java | 16 +- .../cosmos/core/ReactiveCosmosTemplateIT.java | 42 ++-- .../ReactiveCosmosTemplatePartitionIT.java | 10 +- .../ZonedDateTimeDeserializerTest.java | 2 +- .../cosmos/performance/PerfConfiguration.java | 12 +- .../performance/service/SdkService.java | 18 +- .../repository/TestRepositoryConfig.java | 33 ++-- ...ositoryConfigurationExtensionUnitTest.java | 6 +- ...ositoryConfigurationExtensionUnitTest.java | 6 +- .../integration/CosmosAnnotationIT.java | 10 +- .../IntegerIdDomainRepositoryIT.java | 6 +- .../integration/MemoRepositoryIT.java | 4 +- .../PageableAddressRepositoryIT.java | 6 +- .../integration/PageableMemoRepositoryIT.java | 6 +- .../integration/ProjectRepositorySortIT.java | 6 +- .../ReactiveCourseRepositoryIT.java | 8 +- ...ionIT.java => SpELCosmosAnnotationIT.java} | 20 +- .../src/test/resources/application.properties | 8 +- 40 files changed, 490 insertions(+), 500 deletions(-) rename sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/{CosmosDBFactory.java => CosmosFactory.java} (74%) rename sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/{CosmosDbUtils.java => CosmosUtils.java} (78%) rename sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/{CosmosDBConfig.java => CosmosConfig.java} (66%) rename sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/{CosmosDBAccessException.java => CosmosAccessException.java} (85%) rename sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/{CosmosDBExceptionUtils.java => CosmosExceptionUtils.java} (91%) rename sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/{CosmosDBProperties.java => CosmosProperties.java} (94%) rename sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/{CosmosDBFactoryTestIT.java => CosmosFactoryTestIT.java} (79%) rename sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/{SpELCosmosDBAnnotationIT.java => SpELCosmosAnnotationIT.java} (88%) diff --git a/sdk/cosmos/azure-spring-data-cosmos/README.md b/sdk/cosmos/azure-spring-data-cosmos/README.md index 6cabc2e51a72..bcbcf71c8dc3 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/README.md +++ b/sdk/cosmos/azure-spring-data-cosmos/README.md @@ -133,30 +133,30 @@ public class AppConfiguration extends AbstractCosmosConfiguration { private static final Logger logger = LoggerFactory.getLogger(AppConfiguration.class); - @Value("${azure.cosmosdb.uri}") + @Value("${azure.cosmos.uri}") private String uri; - @Value("${azure.cosmosdb.key}") + @Value("${azure.cosmos.key}") private String key; - @Value("${azure.cosmosdb.secondaryKey}") + @Value("${azure.cosmos.secondaryKey}") private String secondaryKey; - @Value("${azure.cosmosdb.database}") + @Value("${azure.cosmos.database}") private String dbName; - @Value("${azure.cosmosdb.queryMetricsEnabled}") + @Value("${azure.cosmos.queryMetricsEnabled}") private boolean queryMetricsEnabled; private CosmosKeyCredential cosmosKeyCredential; - public CosmosDBConfig getConfig() { + public CosmosConfig getConfig() { this.cosmosKeyCredential = new CosmosKeyCredential(key); - CosmosDBConfig cosmosdbConfig = CosmosDBConfig.builder(uri, + CosmosConfig cosmosConfig = CosmosConfig.builder(uri, this.cosmosKeyCredential, dbName).build(); - cosmosdbConfig.setQueryMetricEnabled(queryMetricsEnabled); - cosmosdbConfig.setResponseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()); - return cosmosdbConfig; + cosmosConfig.setQueryMetricEnabled(queryMetricsEnabled); + cosmosConfig.setResponseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()); + return cosmosConfig; } public void switchToSecondaryKey() { @@ -176,12 +176,12 @@ public class AppConfiguration extends AbstractCosmosConfiguration { Or if you want to customize your config: ```java -public CosmosDBConfig getConfig() { +public CosmosConfig getConfig() { this.cosmosKeyCredential = new CosmosKeyCredential(key); - CosmosDBConfig cosmosDbConfig = CosmosDBConfig.builder(uri, this.cosmosKeyCredential, dbName).build(); - cosmosDbConfig.getConnectionPolicy().connectionMode(ConnectionMode.DIRECT); - cosmosDbConfig.getConnectionPolicy().maxPoolSize(1000); - return cosmosDbConfig; + CosmosConfig cosmosConfig = CosmosConfig.builder(uri, this.cosmosKeyCredential, dbName).build(); + cosmosConfig.getConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + cosmosConfig.getConnectionPolicy().maxPoolSize(1000); + return cosmosConfig; } ``` By default, `@EnableCosmosRepositories` will scan the current package for any interfaces that extend one of Spring Data's repository interfaces. Using it to annotate your Configuration class to scan a different root package by `@EnableCosmosRepositories(basePackageClass=UserRepository.class)` if your project layout has multiple projects and it's not finding your repositories. diff --git a/sdk/cosmos/azure-spring-data-cosmos/pom.xml b/sdk/cosmos/azure-spring-data-cosmos/pom.xml index 236a843cc45b..dc96240c398d 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/pom.xml +++ b/sdk/cosmos/azure-spring-data-cosmos/pom.xml @@ -197,7 +197,6 @@ org.springframework:spring-core:[5.2.6.RELEASE] org.springframework:spring-context:[5.2.6.RELEASE] org.springframework.data:spring-data-commons:[2.3.0.RELEASE] - com.microsoft.azure:azure-cosmos:[3.7.3] org.javatuples:javatuples:[1.2] com.fasterxml.jackson.datatype:jackson-datatype-jdk8:[2.10.0] com.fasterxml.jackson.datatype:jackson-datatype-jsr310:[2.10.1] @@ -205,7 +204,6 @@ com.fasterxml.jackson.module:jackson-module-parameter-names:[2.10.0] javax.annotation:javax.annotation-api:[1.3.2] org.apache.commons:commons-lang3:[3.8.1] - com.google.code.findbugs:jsr305:[3.0.2] diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java index 7ce45989023a..d42d03f7d6cb 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java @@ -18,8 +18,8 @@ public final class Constants { public static final String ID_PROPERTY_NAME = "id"; - public static final String COSMOS_MODULE_NAME = "cosmosDb"; - public static final String COSMOS_MODULE_PREFIX = "cosmosDb"; + public static final String COSMOS_MODULE_NAME = "cosmos"; + public static final String COSMOS_MODULE_PREFIX = "cosmos"; public static final String COSMOS_MAPPING_CONTEXT = "cosmosMappingContext"; public static final String USER_AGENT_SUFFIX = "spring-data/"; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDBFactory.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosFactory.java similarity index 74% rename from sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDBFactory.java rename to sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosFactory.java index 4809a439e838..3f59a7b04dd1 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosDBFactory.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosFactory.java @@ -9,7 +9,7 @@ import com.azure.spring.data.cosmos.common.MacAddress; import com.azure.spring.data.cosmos.common.PropertyLoader; import com.azure.spring.data.cosmos.common.TelemetrySender; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import org.apache.commons.lang3.reflect.FieldUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,11 +22,11 @@ /** * Factory class for CosmosDb to create client */ -public class CosmosDBFactory { +public class CosmosFactory { - private static final Logger logger = LoggerFactory.getLogger(CosmosDBFactory.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CosmosFactory.class); - private final CosmosDBConfig config; + private final CosmosConfig config; private static final boolean IS_TELEMETRY_ALLOWED = PropertyLoader.isApplicationTelemetryAllowed(); @@ -47,12 +47,12 @@ private String getUserAgentSuffix() { /** * Validate config and initialization * - * @param cosmosDBConfig cosmosDBConfig + * @param cosmosConfig cosmosConfig */ - public CosmosDBFactory(@NonNull CosmosDBConfig cosmosDBConfig) { - validateConfig(cosmosDBConfig); + public CosmosFactory(@NonNull CosmosConfig cosmosConfig) { + validateConfig(cosmosConfig); - this.config = cosmosDBConfig; + this.config = cosmosConfig; } /** @@ -77,29 +77,29 @@ public CosmosClient getCosmosSyncClient() { return cosmosClientBuilderFromConfig.buildClient(); } - private CosmosClientBuilder getCosmosClientBuilderFromConfig(CosmosDBConfig cosmosDBConfig) { - final CosmosClientBuilder cosmosClientBuilder = cosmosDBConfig.getCosmosClientBuilder(); + private CosmosClientBuilder getCosmosClientBuilderFromConfig(CosmosConfig cosmosConfig) { + final CosmosClientBuilder cosmosClientBuilder = cosmosConfig.getCosmosClientBuilder(); cosmosClientBuilder.contentResponseOnWriteEnabled(true); final String userAgentSuffixValue = getUserAgentSuffixValue(cosmosClientBuilder); final String userAgentSuffix = getUserAgentSuffix() + userAgentSuffixValue; - return cosmosDBConfig.getCosmosClientBuilder().userAgentSuffix(userAgentSuffix); + return cosmosConfig.getCosmosClientBuilder().userAgentSuffix(userAgentSuffix); } private String getUserAgentSuffixValue(CosmosClientBuilder cosmosClientBuilder) { final Field userAgentSuffix = FieldUtils.getDeclaredField(CosmosClientBuilder.class, "userAgentSuffix", true); try { - return (String)userAgentSuffix.get(cosmosClientBuilder); + return (String) userAgentSuffix.get(cosmosClientBuilder); } catch (IllegalAccessException e) { - logger.error("Error occurred while getting userAgentSuffix from CosmosClientBuilder", + LOGGER.error("Error occurred while getting userAgentSuffix from CosmosClientBuilder", e); } return ""; } - private void validateConfig(@NonNull CosmosDBConfig config) { - Assert.hasText(config.getDatabase(), "cosmosDb database should have text!"); + private void validateConfig(@NonNull CosmosConfig config) { + Assert.hasText(config.getDatabase(), "cosmos database should have text!"); } @PostConstruct @@ -113,11 +113,11 @@ private void sendTelemetry() { } /** - * To get config object of cosmosDb + * To get config object of Cosmos * - * @return CosmosDBConfig + * @return CosmosConfig */ - public CosmosDBConfig getConfig() { + public CosmosConfig getConfig() { return config; } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosUtils.java similarity index 78% rename from sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java rename to sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosUtils.java index bf9e10e65586..9678f69d91c1 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosDbUtils.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosUtils.java @@ -12,18 +12,18 @@ /** * Util class to fill and process response diagnostics */ -public class CosmosDbUtils { +public class CosmosUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(CosmosDbUtils.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CosmosUtils.class); /** * Generate ResponseDiagnostics with cosmos and feed response diagnostics * - * @param type of cosmosResponse - * @param responseDiagnosticsProcessor collect Response Diagnostics from API responses and - * then set in {@link ResponseDiagnostics} object. - * @param cosmosDiagnostics response from cosmos - * @param feedResponse response from feed + * @param type of cosmosResponse + * @param responseDiagnosticsProcessor collect Response Diagnostics from API responses and then set in {@link + * ResponseDiagnostics} object. + * @param cosmosDiagnostics response from cosmos + * @param feedResponse response from feed */ public static void fillAndProcessResponseDiagnostics( ResponseDiagnosticsProcessor responseDiagnosticsProcessor, diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfiguration.java index 1885317fc7f6..0885555ac540 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfiguration.java @@ -6,7 +6,7 @@ import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.CosmosClient; import com.azure.spring.data.cosmos.Constants; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.ReactiveCosmosTemplate; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; @@ -18,50 +18,55 @@ import org.springframework.context.annotation.Configuration; /** - * To configure cosmos with client, cosmosDB factory and template + * To configure cosmos with client, cosmos factory and template */ @Configuration public abstract class AbstractCosmosConfiguration extends CosmosConfigurationSupport { /** * Declare CosmosDbFactory bean. + * * @param config of cosmosDbFactory * @return CosmosDbFactory bean */ @Bean - public CosmosDBFactory cosmosDBFactory(CosmosDBConfig config) { - return new CosmosDBFactory(config); + public CosmosFactory cosmosDBFactory(CosmosConfig config) { + return new CosmosFactory(config); } /** * Declare MappingCosmosConverter bean. + * * @param cosmosMappingContext cosmosMappingContext * @return MappingCosmosConverter bean * @throws ClassNotFoundException if the class type is invalid */ @Bean - public MappingCosmosConverter mappingCosmosConverter(CosmosMappingContext cosmosMappingContext) throws ClassNotFoundException { + public MappingCosmosConverter mappingCosmosConverter(CosmosMappingContext cosmosMappingContext) + throws ClassNotFoundException { return new MappingCosmosConverter(cosmosMappingContext, objectMapper); } /** * Declare CosmosClient bean. - * @param cosmosDBFactory cosmosDbFactory + * + * @param cosmosFactory cosmosDbFactory * @return CosmosClient bean */ @Bean - public CosmosAsyncClient cosmosAsyncClient(CosmosDBFactory cosmosDBFactory) { - return cosmosDBFactory.getCosmosAsyncClient(); + public CosmosAsyncClient cosmosAsyncClient(CosmosFactory cosmosFactory) { + return cosmosFactory.getCosmosAsyncClient(); } /** * Declare CosmosSyncClient bean. - * @param cosmosDBFactory cosmosDBFactory + * + * @param cosmosFactory cosmosDBFactory * @return CosmosSyncClient bean */ @Bean - public CosmosClient cosmosClient(CosmosDBFactory cosmosDBFactory) { - return cosmosDBFactory.getCosmosSyncClient(); + public CosmosClient cosmosClient(CosmosFactory cosmosFactory) { + return cosmosFactory.getCosmosSyncClient(); } @Qualifier(Constants.OBJECT_MAPPER_BEAN_NAME) @@ -70,23 +75,29 @@ public CosmosClient cosmosClient(CosmosDBFactory cosmosDBFactory) { /** * Declare CosmosTemplate bean. - * @param cosmosDBFactory cosmosDbFactory + * + * @param cosmosFactory cosmosDbFactory * @param mappingCosmosConverter mappingCosmosConverter * @return CosmosTemplate bean */ @Bean - public CosmosTemplate cosmosTemplate(CosmosDBFactory cosmosDBFactory, MappingCosmosConverter mappingCosmosConverter) { - return new CosmosTemplate(cosmosDBFactory, mappingCosmosConverter, cosmosDBFactory.getConfig().getDatabase()); + public CosmosTemplate cosmosTemplate(CosmosFactory cosmosFactory, + MappingCosmosConverter mappingCosmosConverter) { + return new CosmosTemplate(cosmosFactory, mappingCosmosConverter, + cosmosFactory.getConfig().getDatabase()); } /** * Declare ReactiveCosmosTemplate bean. - * @param cosmosDBFactory cosmosDbFactory + * + * @param cosmosFactory cosmosDbFactory * @param mappingCosmosConverter mappingCosmosConverter * @return ReactiveCosmosTemplate bean */ @Bean - public ReactiveCosmosTemplate reactiveCosmosTemplate(CosmosDBFactory cosmosDBFactory, MappingCosmosConverter mappingCosmosConverter) { - return new ReactiveCosmosTemplate(cosmosDBFactory, mappingCosmosConverter, cosmosDBFactory.getConfig().getDatabase()); + public ReactiveCosmosTemplate reactiveCosmosTemplate(CosmosFactory cosmosFactory, + MappingCosmosConverter mappingCosmosConverter) { + return new ReactiveCosmosTemplate(cosmosFactory, mappingCosmosConverter, + cosmosFactory.getConfig().getDatabase()); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosDBConfig.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfig.java similarity index 66% rename from sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosDBConfig.java rename to sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfig.java index 8c9060d4ec7b..a89a83c0d02e 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosDBConfig.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfig.java @@ -10,7 +10,7 @@ /** * Config properties of CosmosDB */ -public class CosmosDBConfig { +public class CosmosConfig { private final CosmosClientBuilder cosmosClientBuilder; @@ -24,16 +24,17 @@ public class CosmosDBConfig { /** * Initialization + * * @param cosmosClientBuilder must not be {@literal null} * @param database must not be {@literal null} * @param allowTelemetry must not be {@literal null} * @param responseDiagnosticsProcessor must not be {@literal null} * @param queryMetricsEnabled must not be {@literal null} */ - @ConstructorProperties({"cosmosClientBuilder", "database", "allowTelemetry", - "responseDiagnosticsProcessor", "queryMetricsEnabled"}) - public CosmosDBConfig(CosmosClientBuilder cosmosClientBuilder, String database, boolean allowTelemetry, - ResponseDiagnosticsProcessor responseDiagnosticsProcessor, boolean queryMetricsEnabled) { + @ConstructorProperties({ "cosmosClientBuilder", "database", "allowTelemetry", + "responseDiagnosticsProcessor", "queryMetricsEnabled" }) + public CosmosConfig(CosmosClientBuilder cosmosClientBuilder, String database, boolean allowTelemetry, + ResponseDiagnosticsProcessor responseDiagnosticsProcessor, boolean queryMetricsEnabled) { this.cosmosClientBuilder = cosmosClientBuilder; this.database = database; this.allowTelemetry = allowTelemetry; @@ -43,6 +44,7 @@ public CosmosDBConfig(CosmosClientBuilder cosmosClientBuilder, String database, /** * Gets the cosmos client builder used to build cosmos client + * * @return cosmosClientBuilder */ public CosmosClientBuilder getCosmosClientBuilder() { @@ -51,6 +53,7 @@ public CosmosClientBuilder getCosmosClientBuilder() { /** * Checks if telemetry is allowed + * * @return boolean */ public boolean isAllowTelemetry() { @@ -59,6 +62,7 @@ public boolean isAllowTelemetry() { /** * Gets response diagnostics processor + * * @return ResponseDiagnosticsProcessor */ public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { @@ -67,6 +71,7 @@ public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { /** * Gets the option to enable query metrics + * * @return boolean, whether to enable query metrics */ public boolean isQueryMetricsEnabled() { @@ -75,6 +80,7 @@ public boolean isQueryMetricsEnabled() { /** * Gets the database name + * * @return database name */ public String getDatabase() { @@ -82,32 +88,34 @@ public String getDatabase() { } /** - * Create a CosmosDBConfigBuilder instance - * @return CosmosDBConfigBuilder + * Create a CosmosConfigBuilder instance + * + * @return CosmosConfigBuilder */ - public static CosmosDBConfigBuilder builder() { - return new CosmosDBConfigBuilder(); + public static CosmosConfigBuilder builder() { + return new CosmosConfigBuilder(); } /** - * Builder class for cosmos db config + * Builder class for cosmos config */ - public static class CosmosDBConfigBuilder { + public static class CosmosConfigBuilder { private String database; private CosmosClientBuilder cosmosClientBuilder; private boolean allowTelemetry; private ResponseDiagnosticsProcessor responseDiagnosticsProcessor; private boolean queryMetricsEnabled; - CosmosDBConfigBuilder() { + CosmosConfigBuilder() { } /** * Set cosmosClientBuilder to use to build cosmos client + * * @param cosmosClientBuilder cosmos client builder - * @return CosmosDBConfigBuilder + * @return CosmosConfigBuilder */ - public CosmosDBConfigBuilder cosmosClientBuilder(CosmosClientBuilder cosmosClientBuilder) { + public CosmosConfigBuilder cosmosClientBuilder(CosmosClientBuilder cosmosClientBuilder) { this.cosmosClientBuilder = cosmosClientBuilder; return this; } @@ -116,9 +124,9 @@ public CosmosDBConfigBuilder cosmosClientBuilder(CosmosClientBuilder cosmosClien * Set allowTelemetry * * @param allowTelemetry value to initialize - * @return CosmosDBConfigBuilder + * @return CosmosConfigBuilder */ - public CosmosDBConfigBuilder allowTelemetry(boolean allowTelemetry) { + public CosmosConfigBuilder allowTelemetry(boolean allowTelemetry) { this.allowTelemetry = allowTelemetry; return this; } @@ -127,10 +135,10 @@ public CosmosDBConfigBuilder allowTelemetry(boolean allowTelemetry) { * Set responseDiagnosticsProcessor * * @param responseDiagnosticsProcessor value to initialize - * @return CosmosDBConfigBuilder + * @return CosmosConfigBuilder */ - public CosmosDBConfigBuilder responseDiagnosticsProcessor(ResponseDiagnosticsProcessor - responseDiagnosticsProcessor) { + public CosmosConfigBuilder responseDiagnosticsProcessor(ResponseDiagnosticsProcessor + responseDiagnosticsProcessor) { this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; return this; } @@ -139,9 +147,9 @@ public CosmosDBConfigBuilder responseDiagnosticsProcessor(ResponseDiagnosticsPro * Set queryMetricsEnabled * * @param queryMetricsEnabled value to initialize - * @return CosmosDBConfigBuilder + * @return CosmosConfigBuilder */ - public CosmosDBConfigBuilder enableQueryMetrics(boolean queryMetricsEnabled) { + public CosmosConfigBuilder enableQueryMetrics(boolean queryMetricsEnabled) { this.queryMetricsEnabled = queryMetricsEnabled; return this; } @@ -150,32 +158,32 @@ public CosmosDBConfigBuilder enableQueryMetrics(boolean queryMetricsEnabled) { * Sets the database * * @param database database name - * @return CosmosDBConfigBuilder + * @return CosmosConfigBuilder */ - public CosmosDBConfigBuilder database(String database) { + public CosmosConfigBuilder database(String database) { this.database = database; return this; } /** - * Build a CosmosDBConfig instance + * Build a CosmosConfig instance * - * @return CosmosDBConfig + * @return CosmosConfig */ - public CosmosDBConfig build() { - return new CosmosDBConfig(this.cosmosClientBuilder, this.database, this.allowTelemetry, + public CosmosConfig build() { + return new CosmosConfig(this.cosmosClientBuilder, this.database, this.allowTelemetry, this.responseDiagnosticsProcessor, this.queryMetricsEnabled); } @Override public String toString() { - return "CosmosDBConfigBuilder{" + - "database='" + database + '\'' + - ", cosmosClientBuilder=" + cosmosClientBuilder + - ", allowTelemetry=" + allowTelemetry + - ", responseDiagnosticsProcessor=" + responseDiagnosticsProcessor + - ", queryMetricsEnabled=" + queryMetricsEnabled + - '}'; + return "CosmosConfigBuilder{" + + "database='" + database + '\'' + + ", cosmosClientBuilder=" + cosmosClientBuilder + + ", allowTelemetry=" + allowTelemetry + + ", responseDiagnosticsProcessor=" + responseDiagnosticsProcessor + + ", queryMetricsEnabled=" + queryMetricsEnabled + + '}'; } } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java index bbd5e2eddd4b..f24b8cb304c0 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/CosmosTemplate.java @@ -15,8 +15,8 @@ import com.azure.cosmos.models.PartitionKey; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.models.ThroughputProperties; -import com.azure.spring.data.cosmos.CosmosDBFactory; -import com.azure.spring.data.cosmos.common.CosmosDbUtils; +import com.azure.spring.data.cosmos.CosmosFactory; +import com.azure.spring.data.cosmos.common.CosmosUtils; import com.azure.spring.data.cosmos.common.Memoizer; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.generator.CountQueryGenerator; @@ -26,7 +26,7 @@ import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; import com.azure.spring.data.cosmos.core.query.DocumentQuery; -import com.azure.spring.data.cosmos.exception.CosmosDBExceptionUtils; +import com.azure.spring.data.cosmos.exception.CosmosExceptionUtils; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.fasterxml.jackson.databind.JsonNode; import org.slf4j.Logger; @@ -69,23 +69,23 @@ public class CosmosTemplate implements CosmosOperations, ApplicationContextAware /** * Initialization * - * @param cosmosDbFactory must not be {@literal null} + * @param cosmosFactory must not be {@literal null} * @param mappingCosmosConverter must not be {@literal null} - * @param dbName must not be {@literal null} + * @param dbName must not be {@literal null} */ - public CosmosTemplate(CosmosDBFactory cosmosDbFactory, + public CosmosTemplate(CosmosFactory cosmosFactory, MappingCosmosConverter mappingCosmosConverter, String dbName) { - Assert.notNull(cosmosDbFactory, "CosmosDbFactory must not be null!"); + Assert.notNull(cosmosFactory, "CosmosDbFactory must not be null!"); Assert.notNull(mappingCosmosConverter, "MappingCosmosConverter must not be null!"); this.mappingCosmosConverter = mappingCosmosConverter; this.databaseName = dbName; - this.cosmosAsyncClient = cosmosDbFactory.getCosmosAsyncClient(); + this.cosmosAsyncClient = cosmosFactory.getCosmosAsyncClient(); this.responseDiagnosticsProcessor = - cosmosDbFactory.getConfig().getResponseDiagnosticsProcessor(); - this.enableQueryMetrics = cosmosDbFactory.getConfig().isQueryMetricsEnabled(); + cosmosFactory.getConfig().getResponseDiagnosticsProcessor(); + this.enableQueryMetrics = cosmosFactory.getConfig().isQueryMetricsEnabled(); } /** @@ -102,7 +102,7 @@ public void setApplicationContext(ApplicationContext applicationContext) throws * * @param objectToSave must not be {@literal null} * @param partitionKey must not be {@literal null} - * @param type class of domain type + * @param type class of domain type * @return the inserted item */ public T insert(T objectToSave, PartitionKey partitionKey) { @@ -115,36 +115,33 @@ public T insert(T objectToSave, PartitionKey partitionKey) { * Inserts item into the given container * * @param containerName must not be {@literal null} - * @param objectToSave must not be {@literal null} - * @param partitionKey must not be {@literal null} - * @param type class of domain type + * @param objectToSave must not be {@literal null} + * @param partitionKey must not be {@literal null} + * @param type class of domain type * @return the inserted item */ public T insert(String containerName, T objectToSave, PartitionKey partitionKey) { - Assert.hasText(containerName, "containerName should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); Assert.notNull(objectToSave, "objectToSave should not be null"); - final JsonNode originalItem = - mappingCosmosConverter.writeJsonNode(objectToSave); + final JsonNode originalItem = mappingCosmosConverter.writeJsonNode(objectToSave); LOGGER.debug("execute createItem in database {} container {}", this.databaseName, containerName); final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - @SuppressWarnings("unchecked") final Class domainType = - (Class)objectToSave.getClass(); + @SuppressWarnings("unchecked") final Class domainType = (Class) objectToSave.getClass(); final CosmosItemResponse response = cosmosAsyncClient .getDatabase(this.databaseName) .getContainer(containerName) .createItem(originalItem, partitionKey, options) .doOnNext(cosmosItemResponse -> - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to insert item", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to insert item", throwable)) .block(); assert response != null; @@ -154,9 +151,9 @@ public T insert(String containerName, T objectToSave, PartitionKey partition /** * Finds item by id * - * @param id must not be {@literal null} + * @param id must not be {@literal null} * @param domainType must not be {@literal null} - * @param type class of domain type + * @param type class of domain type * @return found item */ public T findById(Object id, Class domainType) { @@ -177,12 +174,12 @@ public T findById(Object id, Class domainType, PartitionKey partitionKey) .getContainer(containerName) .readItem(id.toString(), partitionKey, JsonNode.class) .flatMap(cosmosItemResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.justOrEmpty(toDomainObject(domainType, cosmosItemResponse.getItem())); }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) + CosmosExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) .block(); } @@ -190,14 +187,13 @@ public T findById(Object id, Class domainType, PartitionKey partitionKey) * Finds item by id * * @param containerName must not be {@literal null} - * @param id must not be {@literal null} - * @param domainType must not be {@literal null} - * @param type class of domain type + * @param id must not be {@literal null} + * @param domainType must not be {@literal null} + * @param type class of domain type * @return found item */ public T findById(String containerName, Object id, Class domainType) { - Assert.hasText(containerName, "containerName should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); Assert.notNull(domainType, "domainType should not be null"); assertValidId(id); @@ -211,7 +207,7 @@ public T findById(String containerName, Object id, Class domainType) { .queryItems(query, options, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Mono.justOrEmpty(cosmosItemFeedResponse .getResults() @@ -220,7 +216,7 @@ public T findById(String containerName, Object id, Class domainType) { .findFirst()); }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) + CosmosExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) .blockFirst(); } @@ -228,7 +224,7 @@ public T findById(String containerName, Object id, Class domainType) { * Upserts an item with partition key * * @param object upsert object - * @param type of upsert object + * @param type of upsert object */ public void upsert(T object) { Assert.notNull(object, "Upsert object should not be null"); @@ -240,8 +236,8 @@ public void upsert(T object) { * Upserts an item into container with partition key * * @param containerName the container name - * @param object upsert object - * @param type of upsert object + * @param object upsert object + * @param type of upsert object */ public void upsert(String containerName, T object) { upsertAndReturnEntity(containerName, object); @@ -251,13 +247,12 @@ public void upsert(String containerName, T object) { * Upserts an item and return item properties * * @param containerName the container name - * @param object upsert object - * @param type of upsert object + * @param object upsert object + * @param type of upsert object * @return upsert object entity */ public T upsertAndReturnEntity(String containerName, T object) { - Assert.hasText(containerName, "containerName should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); Assert.notNull(object, "Upsert object should not be null"); final JsonNode originalItem = mappingCosmosConverter.writeJsonNode(object); @@ -265,7 +260,7 @@ public T upsertAndReturnEntity(String containerName, T object) { LOGGER.debug("execute upsert item in database {} container {}", this.databaseName, containerName); - @SuppressWarnings("unchecked") final Class domainType = (Class)object.getClass(); + @SuppressWarnings("unchecked") final Class domainType = (Class) object.getClass(); final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); applyVersioning(domainType, originalItem, options); @@ -274,10 +269,10 @@ public T upsertAndReturnEntity(String containerName, T object) { .getDatabase(this.databaseName) .getContainer(containerName) .upsertItem(originalItem, options) - .doOnNext(response -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + .doOnNext(response -> CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, response.getDiagnostics(), null)) - .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to upsert" + - " item", throwable)) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to upsert item", throwable)) .block(); assert cosmosItemResponse != null; @@ -288,7 +283,7 @@ public T upsertAndReturnEntity(String containerName, T object) { * Find the DocumentQuery, find all the items specified by domain type. * * @param domainType the domain type - * @param class type of domain + * @param class type of domain * @return found results in a List */ public List findAll(Class domainType) { @@ -301,13 +296,12 @@ public List findAll(Class domainType) { * Find the DocumentQuery, find all the items specified by domain type in the given container. * * @param containerName the container name - * @param domainType the domain type - * @param class type of domain + * @param domainType the domain type + * @param class type of domain * @return found results in a List */ public List findAll(String containerName, final Class domainType) { - Assert.hasText(containerName, "containerName should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); Assert.notNull(domainType, "domainType should not be null"); final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)); @@ -335,13 +329,13 @@ public List findAll(PartitionKey partitionKey, final Class domainType) .queryItems("SELECT * FROM r", cosmosQueryRequestOptions, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, cosmosItemFeedResponse); return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) .map(jsonNode -> toDomainObject(domainType, jsonNode)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to find items", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to find items", throwable)) .collectList() .block(); } @@ -350,11 +344,10 @@ public List findAll(PartitionKey partitionKey, final Class domainType) * Delete the DocumentQuery, delete all the items in the given container. * * @param containerName Container name of database - * @param domainType the domain type + * @param domainType the domain type */ public void deleteAll(@NonNull String containerName, @NonNull Class domainType) { - Assert.hasText(containerName, "containerName should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)); @@ -368,12 +361,11 @@ public void deleteContainer(@NonNull String containerName) { .getContainer(containerName) .delete() .doOnNext(response -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, response.getDiagnostics(), null); }) - .onErrorResume(throwable -> CosmosDBExceptionUtils.exceptionHandler("Failed to delete " + - "container", - throwable)) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to delete container", throwable)) .block(); } @@ -389,9 +381,9 @@ public CosmosContainerProperties createContainerIfNotExists(CosmosEntityInformat final CosmosContainerResponse response = cosmosAsyncClient .createDatabaseIfNotExists(this.databaseName) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to create database", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to create database", throwable)) .flatMap(cosmosDatabaseResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosDatabaseResponse.getDiagnostics(), null); final CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties( @@ -417,10 +409,10 @@ public CosmosContainerProperties createContainerIfNotExists(CosmosEntityInformat return cosmosContainerResponseMono .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to create container", + CosmosExceptionUtils.exceptionHandler("Failed to create container", throwable)) .doOnNext(cosmosContainerResponse -> - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosContainerResponse.getDiagnostics(), null)); }) .block(); @@ -429,16 +421,14 @@ public CosmosContainerProperties createContainerIfNotExists(CosmosEntityInformat } /** - * Delete the DocumentQuery, need to query by id at first, then delete the item - * from the result. + * Delete the DocumentQuery, need to query by id at first, then delete the item from the result. * * @param containerName Container name of database - * @param id item id - * @param partitionKey the partition key + * @param id item id + * @param partitionKey the partition key */ public void deleteById(String containerName, Object id, PartitionKey partitionKey) { - Assert.hasText(containerName, "containerName should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); assertValidId(id); LOGGER.debug("execute deleteById in database {} container {}", this.databaseName, @@ -450,10 +440,11 @@ public void deleteById(String containerName, Object id, PartitionKey partitionKe cosmosAsyncClient.getDatabase(this.databaseName) .getContainer(containerName) .deleteItem(id.toString(), partitionKey) - .doOnNext(response -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - response.getDiagnostics(), null)) + .doOnNext(response -> + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + response.getDiagnostics(), null)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", + CosmosExceptionUtils.exceptionHandler("Failed to delete item", throwable)) .block(); } @@ -472,10 +463,10 @@ public List findByIds(Iterable ids, Class domainType, String c /** * Finds the document query items * - * @param query The representation for query method. - * @param domainType Class of domain + * @param query The representation for query method. + * @param domainType Class of domain * @param containerName Container name of database - * @param class of domainType + * @param class of domainType * @return All the found items as List. */ public List find(@NonNull DocumentQuery query, @NonNull Class domainType, @@ -493,10 +484,10 @@ public List find(@NonNull DocumentQuery query, @NonNull Class domainTy /** * Checks if document query items exist * - * @param query The representation for query method. - * @param domainType Class of domain + * @param query The representation for query method. + * @param domainType Class of domain * @param containerName Container name of database - * @param class of domainType + * @param class of domainType * @return if items exist */ public Boolean exists(@NonNull DocumentQuery query, @NonNull Class domainType, @@ -505,14 +496,13 @@ public Boolean exists(@NonNull DocumentQuery query, @NonNull Class domain } /** - * Delete the DocumentQuery, need to query the domains at first, then delete the item - * from the result. - * The cosmos db Sql API do _NOT_ support DELETE query, we cannot add one DeleteQueryGenerator. + * Delete the DocumentQuery, need to query the domains at first, then delete the item from the result. The cosmos db + * Sql API do _NOT_ support DELETE query, we cannot add one DeleteQueryGenerator. * - * @param query The representation for query method. - * @param domainType Class of domain + * @param query The representation for query method. + * @param domainType Class of domain * @param containerName Container name of database - * @param class of domainType + * @param class of domainType * @return All the deleted items as List. */ @Override @@ -544,8 +534,8 @@ public Page findAll(Pageable pageable, Class domainType, String contai @Override public Page paginationQuery(DocumentQuery query, Class domainType, String containerName) { - Assert.isTrue(query.getPageable().getPageSize() > 0, "pageable should have page size " + - "larger than 0"); + Assert.isTrue(query.getPageable().getPageSize() > 0, + "pageable should have page size larger than 0"); Assert.hasText(containerName, "container should not be null, empty or only whitespaces"); final Pageable pageable = query.getPageable(); @@ -560,7 +550,7 @@ public Page paginationQuery(DocumentQuery query, Class domainType, if (pageable instanceof CosmosPageRequest) { feedResponseFlux = container .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) - .byPage(((CosmosPageRequest)pageable).getRequestContinuation(), + .byPage(((CosmosPageRequest) pageable).getRequestContinuation(), pageable.getPageSize()); } else { feedResponseFlux = container @@ -570,10 +560,10 @@ public Page paginationQuery(DocumentQuery query, Class domainType, final FeedResponse feedResponse = feedResponseFlux .doOnNext(propertiesFeedResponse -> - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, propertiesFeedResponse.getCosmosDiagnostics(), propertiesFeedResponse)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to query items", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to query items", throwable)) .next() .block(); @@ -650,8 +640,8 @@ private Long getCountValue(DocumentQuery query, String containerName) { return executeQuery(querySpec, containerName, options) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to get count value", throwable)) - .doOnNext(response -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosExceptionUtils.exceptionHandler("Failed to get count value", throwable)) + .doOnNext(response -> CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, response)) .next() .map(r -> r.getResults().get(0).asLong()) @@ -666,8 +656,8 @@ private Flux> executeQuery(SqlQuerySpec sqlQuerySpec, .queryItems(sqlQuerySpec, options, JsonNode.class) .byPage() .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to execute " + - "query", throwable)); + CosmosExceptionUtils.exceptionHandler("Failed to execute query", + throwable)); } private List getPartitionKeyNames(Class domainType) { @@ -699,12 +689,12 @@ private List findItems(@NonNull DocumentQuery query, .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to find items", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to find items", throwable)) .collectList() .block(); } @@ -733,10 +723,10 @@ private T deleteItem(@NonNull JsonNode jsonNode, .getDatabase(this.databaseName) .getContainer(containerName) .deleteItem(jsonNode.get("id").asText(), partitionKey) - .doOnNext(response -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + .doOnNext(response -> CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, response.getDiagnostics(), null)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete item", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to delete item", throwable)) .flatMap(objectCosmosItemResponse -> Mono.just(toDomainObject(domainType, jsonNode))) .block(); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java index c12b9859b3ca..b1e7eaf6dd2d 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplate.java @@ -13,8 +13,8 @@ import com.azure.cosmos.models.PartitionKey; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.models.ThroughputProperties; -import com.azure.spring.data.cosmos.CosmosDBFactory; -import com.azure.spring.data.cosmos.common.CosmosDbUtils; +import com.azure.spring.data.cosmos.CosmosFactory; +import com.azure.spring.data.cosmos.common.CosmosUtils; import com.azure.spring.data.cosmos.common.Memoizer; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.generator.CountQueryGenerator; @@ -22,7 +22,7 @@ import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; import com.azure.spring.data.cosmos.core.query.DocumentQuery; -import com.azure.spring.data.cosmos.exception.CosmosDBExceptionUtils; +import com.azure.spring.data.cosmos.exception.CosmosExceptionUtils; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import com.fasterxml.jackson.databind.JsonNode; import org.springframework.beans.BeansException; @@ -58,23 +58,23 @@ public class ReactiveCosmosTemplate implements ReactiveCosmosOperations, Applica /** * Constructor * - * @param cosmosDbFactory the cosmos db factory + * @param cosmosFactory the cosmos db factory * @param mappingCosmosConverter the mappingCosmosConverter - * @param dbName database name + * @param dbName database name */ - public ReactiveCosmosTemplate(CosmosDBFactory cosmosDbFactory, + public ReactiveCosmosTemplate(CosmosFactory cosmosFactory, MappingCosmosConverter mappingCosmosConverter, String dbName) { - Assert.notNull(cosmosDbFactory, "CosmosDbFactory must not be null!"); + Assert.notNull(cosmosFactory, "CosmosDbFactory must not be null!"); Assert.notNull(mappingCosmosConverter, "MappingCosmosConverter must not be null!"); this.mappingCosmosConverter = mappingCosmosConverter; this.databaseName = dbName; - this.cosmosAsyncClient = cosmosDbFactory.getCosmosAsyncClient(); + this.cosmosAsyncClient = cosmosFactory.getCosmosAsyncClient(); this.responseDiagnosticsProcessor = - cosmosDbFactory.getConfig().getResponseDiagnosticsProcessor(); - this.isPopulateQueryMetrics = cosmosDbFactory.getConfig().isQueryMetricsEnabled(); + cosmosFactory.getConfig().getResponseDiagnosticsProcessor(); + this.isPopulateQueryMetrics = cosmosFactory.getConfig().isQueryMetricsEnabled(); } /** @@ -97,9 +97,9 @@ public Mono createContainerIfNotExists(CosmosEntityInfo return cosmosAsyncClient .createDatabaseIfNotExists(this.databaseName) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to create database", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to create database", throwable)) .flatMap(cosmosDatabaseResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosDatabaseResponse.getDiagnostics(), null); final CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties( @@ -125,12 +125,12 @@ public Mono createContainerIfNotExists(CosmosEntityInfo return cosmosContainerResponseMono .map(cosmosContainerResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosContainerResponse.getDiagnostics(), null); return cosmosContainerResponse; }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to create container", + CosmosExceptionUtils.exceptionHandler("Failed to create container", throwable)); }); @@ -140,7 +140,7 @@ public Mono createContainerIfNotExists(CosmosEntityInfo * Find all items in a given container * * @param containerName the containerName - * @param domainType the domainType + * @param domainType the domainType * @return Flux with all the found items or error */ @Override @@ -178,19 +178,19 @@ public Flux findAll(PartitionKey partitionKey, Class domainType) { .queryItems("SELECT * FROM r", cosmosQueryRequestOptions, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) .map(cosmosItemProperties -> toDomainObject(domainType, cosmosItemProperties)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to find items", throwable)); + CosmosExceptionUtils.exceptionHandler("Failed to find items", throwable)); } /** * Find by id * - * @param id the id + * @param id the id * @param domainType the domainType * @return Mono with the item or error */ @@ -204,14 +204,13 @@ public Mono findById(Object id, Class domainType) { * Find by id * * @param containerName the container name - * @param id the id - * @param domainType the entity class + * @param id the id + * @param domainType the entity class * @return Mono with the item or error */ @Override public Mono findById(String containerName, Object id, Class domainType) { - Assert.hasText(containerName, "containerName should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); Assert.notNull(domainType, "domainType should not be null"); assertValidId(id); @@ -225,7 +224,7 @@ public Mono findById(String containerName, Object id, Class domainType .queryItems(query, options, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); return Mono.justOrEmpty(cosmosItemFeedResponse @@ -235,16 +234,15 @@ public Mono findById(String containerName, Object id, Class domainType .findFirst()); }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to " + - "find item", throwable)) + CosmosExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) .next(); } /** * Find by id * - * @param id the id - * @param domainType the entity class + * @param id the id + * @param domainType the entity class * @param partitionKey partition Key * @return Mono with the item or error */ @@ -258,20 +256,19 @@ public Mono findById(Object id, Class domainType, PartitionKey partiti .getContainer(containerName) .readItem(id.toString(), partitionKey, JsonNode.class) .flatMap(cosmosItemResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.justOrEmpty(toDomainObject(domainType, cosmosItemResponse.getItem())); }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to " + - "find item", throwable)); + CosmosExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)); } /** * Insert * - * @param type of inserted objectToSave + * @param type of inserted objectToSave * @param objectToSave the object to save * @param partitionKey the partition key * @return Mono with the item or error @@ -286,23 +283,22 @@ public Mono insert(T objectToSave, PartitionKey partitionKey) { * Insert * * @param objectToSave the object to save - * @param type of inserted objectToSave + * @param type of inserted objectToSave * @return Mono with the item or error */ public Mono insert(T objectToSave) { Assert.notNull(objectToSave, "objectToSave should not be null"); - final Class domainType = (Class)objectToSave.getClass(); + final Class domainType = (Class) objectToSave.getClass(); final JsonNode originalItem = mappingCosmosConverter.writeJsonNode(objectToSave); return cosmosAsyncClient.getDatabase(this.databaseName) .getContainer(getContainerName(objectToSave.getClass())) .createItem(originalItem, new CosmosItemRequestOptions()) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to insert " + - "item", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to insert item", throwable)) .flatMap(cosmosItemResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.just(toDomainObject(domainType, cosmosItemResponse.getItem())); @@ -312,19 +308,18 @@ public Mono insert(T objectToSave) { /** * Insert * - * @param type of inserted objectToSave + * @param type of inserted objectToSave * @param containerName the container name - * @param objectToSave the object to save - * @param partitionKey the partition key + * @param objectToSave the object to save + * @param partitionKey the partition key * @return Mono with the item or error */ public Mono insert(String containerName, Object objectToSave, PartitionKey partitionKey) { - Assert.hasText(containerName, "containerName should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "containerName should not be null, empty or only whitespaces"); Assert.notNull(objectToSave, "objectToSave should not be null"); - final Class domainType = (Class)objectToSave.getClass(); + final Class domainType = (Class) objectToSave.getClass(); final JsonNode originalItem = mappingCosmosConverter.writeJsonNode(objectToSave); final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); @@ -335,10 +330,9 @@ public Mono insert(String containerName, Object objectToSave, .getContainer(containerName) .createItem(originalItem, partitionKey, options) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to insert " + - "item", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to insert item", throwable)) .flatMap(cosmosItemResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.just(toDomainObject(domainType, cosmosItemResponse.getItem())); @@ -360,12 +354,12 @@ public Mono upsert(T object) { * Upsert * * @param containerName the container name - * @param object the object to save + * @param object the object to save * @return Mono with the item or error */ @Override public Mono upsert(String containerName, T object) { - final Class domainType = (Class)object.getClass(); + final Class domainType = (Class) object.getClass(); final JsonNode originalItem = mappingCosmosConverter.writeJsonNode(object); final CosmosItemRequestOptions options = new CosmosItemRequestOptions(); @@ -376,28 +370,26 @@ public Mono upsert(String containerName, T object) { .getContainer(containerName) .upsertItem(originalItem, options) .flatMap(cosmosItemResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return Mono.just(toDomainObject(domainType, cosmosItemResponse.getItem())); }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to upsert " + - "item", throwable)); + CosmosExceptionUtils.exceptionHandler("Failed to upsert item", throwable)); } /** * Delete an item by id * * @param containerName the container name - * @param id the id - * @param partitionKey the partition key + * @param id the id + * @param partitionKey the partition key * @return void Mono */ @Override public Mono deleteById(String containerName, Object id, PartitionKey partitionKey) { - Assert.hasText(containerName, "container name should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "container name should not be null, empty or only whitespaces"); assertValidId(id); if (partitionKey == null) { @@ -408,11 +400,10 @@ public Mono deleteById(String containerName, Object id, PartitionKey parti .getContainer(containerName) .deleteItem(id.toString(), partitionKey) .doOnNext(cosmosItemResponse -> - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete " + - "item", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to delete item", throwable)) .then(); } @@ -420,13 +411,12 @@ public Mono deleteById(String containerName, Object id, PartitionKey parti * Delete all items in a container * * @param containerName the container name - * @param domainType the domainType + * @param domainType the domainType * @return void Mono */ @Override public Mono deleteAll(@NonNull String containerName, @NonNull Class domainType) { - Assert.hasText(containerName, "container name should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "container name should not be null, empty or only whitespaces"); final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)); @@ -436,8 +426,8 @@ public Mono deleteAll(@NonNull String containerName, @NonNull Class dom /** * Delete items matching query * - * @param query the document query - * @param domainType the entity class + * @param query the document query + * @param domainType the entity class * @param containerName the container name * @return Mono */ @@ -445,8 +435,7 @@ public Mono deleteAll(@NonNull String containerName, @NonNull Class dom public Flux delete(DocumentQuery query, Class domainType, String containerName) { Assert.notNull(query, "DocumentQuery should not be null."); Assert.notNull(domainType, "domainType should not be null."); - Assert.hasText(containerName, "container name should not be null, empty or only " + - "whitespaces"); + Assert.hasText(containerName, "container name should not be null, empty or only whitespaces"); final Flux results = findItems(query, containerName); final List partitionKeyName = getPartitionKeyNames(domainType); @@ -457,8 +446,8 @@ public Flux delete(DocumentQuery query, Class domainType, String conta /** * Find items * - * @param query the document query - * @param domainType the entity class + * @param query the document query + * @param domainType the entity class * @param containerName the container name * @return Flux with found items or error */ @@ -471,8 +460,8 @@ public Flux find(DocumentQuery query, Class domainType, String contain /** * Exists * - * @param query the document query - * @param domainType the entity class + * @param query the document query + * @param domainType the entity class * @param containerName the container name * @return Mono with a boolean or error */ @@ -484,8 +473,8 @@ public Mono exists(DocumentQuery query, Class domainType, String con /** * Exists * - * @param id the id - * @param domainType the entity class + * @param id the id + * @param domainType the entity class * @param containerName the container name * @return Mono with a boolean or error */ @@ -509,7 +498,7 @@ public Mono count(String containerName) { /** * Count * - * @param query the document query + * @param query the document query * @param containerName the container name * @return Mono with count or error */ @@ -530,10 +519,10 @@ private Mono getCountValue(DocumentQuery query, String containerName) { options.setQueryMetricsEnabled(isPopulateQueryMetrics); return executeQuery(querySpec, containerName, options) - .doOnNext(feedResponse -> CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + .doOnNext(feedResponse -> CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, feedResponse)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to get count value", throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to get count value", throwable)) .next() .map(r -> r.getResults().get(0).asLong()); } @@ -547,8 +536,7 @@ private Flux> executeQuery(SqlQuerySpec sqlQuerySpec, .queryItems(sqlQuerySpec, options, JsonNode.class) .byPage() .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to execute " + - "query", throwable)); + CosmosExceptionUtils.exceptionHandler("Failed to execute query", throwable)); } /** @@ -563,11 +551,11 @@ public void deleteContainer(@NonNull String containerName) { .getContainer(containerName) .delete() .doOnNext(cosmosContainerResponse -> - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosContainerResponse.getDiagnostics(), null)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete container" - , throwable)) + CosmosExceptionUtils.exceptionHandler("Failed to delete container", + throwable)) .block(); } @@ -593,12 +581,12 @@ private Flux findItems(@NonNull DocumentQuery query, .queryItems(sqlQuerySpec, cosmosQueryRequestOptions, JsonNode.class) .byPage() .flatMap(cosmosItemFeedResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, null, cosmosItemFeedResponse); return Flux.fromIterable(cosmosItemFeedResponse.getResults()); }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to query items", throwable)); + CosmosExceptionUtils.exceptionHandler("Failed to query items", throwable)); } private void assertValidId(Object id) { @@ -638,14 +626,13 @@ private Mono deleteItem(@NonNull JsonNode jsonNode, .getContainer(containerName) .deleteItem(jsonNode.get("id").asText(), partitionKey) .map(cosmosItemResponse -> { - CosmosDbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, cosmosItemResponse.getDiagnostics(), null); return cosmosItemResponse; }) .flatMap(objectCosmosItemResponse -> Mono.just(toDomainObject(domainType, jsonNode))) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to delete " + - "item", throwable)); + CosmosExceptionUtils.exceptionHandler("Failed to delete item", throwable)); } private T toDomainObject(@NonNull Class domainType, JsonNode jsonNode) { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnostics.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnostics.java index ee59400a293f..251eb6b40251 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnostics.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/ResponseDiagnostics.java @@ -17,7 +17,7 @@ public class ResponseDiagnostics { /** * Initialization * - * @param cosmosDiagnostics cannot be null + * @param cosmosDiagnostics cannot be null * @param cosmosResponseStatistics cannot be null */ public ResponseDiagnostics(CosmosDiagnostics cosmosDiagnostics, @@ -93,7 +93,7 @@ public static class CosmosResponseStatistics { * Initialization * * @param feedResponse response from feed - * @param type of cosmosResponse + * @param type of cosmosResponse */ public CosmosResponseStatistics(FeedResponse feedResponse) { this.requestCharge = feedResponse.getRequestCharge(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/convert/MappingCosmosConverter.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/convert/MappingCosmosConverter.java index 94c927e1eef8..260adf81ceb9 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/convert/MappingCosmosConverter.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/core/convert/MappingCosmosConverter.java @@ -5,7 +5,7 @@ import com.azure.spring.data.cosmos.Constants; import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentEntity; import com.azure.spring.data.cosmos.core.mapping.CosmosPersistentProperty; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; +import com.azure.spring.data.cosmos.exception.CosmosAccessException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -46,7 +46,7 @@ public class MappingCosmosConverter * Initialization * * @param mappingContext must not be {@literal null} - * @param objectMapper must not be {@literal null} + * @param objectMapper must not be {@literal null} */ public MappingCosmosConverter( MappingContext, CosmosPersistentProperty> mappingContext, @@ -96,8 +96,8 @@ private R readInternal(final CosmosPersistentEntity entity, Class type * * @param sourceEntity must not be {@literal null} * @return CosmosItemProperties - * @throws MappingException no mapping metadata for entity type - * @throws CosmosDBAccessException fail to map document value + * @throws MappingException no mapping metadata for entity type + * @throws CosmosAccessException fail to map document value */ public JsonNode writeJsonNode(Object sourceEntity) { if (sourceEntity == null) { @@ -117,10 +117,9 @@ public JsonNode writeJsonNode(Object sourceEntity) { final ObjectNode cosmosObjectNode; try { - cosmosObjectNode = - (ObjectNode)objectMapper.readTree(objectMapper.writeValueAsString(sourceEntity)); + cosmosObjectNode = (ObjectNode) objectMapper.readTree(objectMapper.writeValueAsString(sourceEntity)); } catch (JsonProcessingException e) { - throw new CosmosDBAccessException("Failed to map document value.", e); + throw new CosmosAccessException("Failed to map document value.", e); } if (idProperty != null) { @@ -186,9 +185,9 @@ public static Object toCosmosDbValue(Object fromPropertyValue) { // Date and Enum correctly if (fromPropertyValue instanceof Date) { - fromPropertyValue = ((Date)fromPropertyValue).getTime(); + fromPropertyValue = ((Date) fromPropertyValue).getTime(); } else if (fromPropertyValue instanceof ZonedDateTime) { - fromPropertyValue = ((ZonedDateTime)fromPropertyValue) + fromPropertyValue = ((ZonedDateTime) fromPropertyValue) .format(DateTimeFormatter.ofPattern(ISO_8601_COMPATIBLE_DATE_PATTERN)); } else if (fromPropertyValue instanceof Enum) { fromPropertyValue = fromPropertyValue.toString(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBAccessException.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosAccessException.java similarity index 85% rename from sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBAccessException.java rename to sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosAccessException.java index ab4de49617a2..6f5b420d2cd7 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBAccessException.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosAccessException.java @@ -12,12 +12,12 @@ * Public class extending DataAccessException, exposes innerException. * Every API in {@link CosmosRepository} * and {@link ReactiveCosmosRepository} - * should throw {@link CosmosDBAccessException}. + * should throw {@link CosmosAccessException}. * innerException refers to the exception thrown by CosmosDB SDK. Callers of repository APIs can * rely on innerException for any retriable logic, or for more details on the failure of * the operation. */ -public class CosmosDBAccessException extends DataAccessException { +public class CosmosAccessException extends DataAccessException { protected final CosmosException cosmosException; @@ -25,7 +25,7 @@ public class CosmosDBAccessException extends DataAccessException { * Construct a {@code CosmosDBAccessException} with the specified detail message. * @param msg the detail message */ - public CosmosDBAccessException(String msg) { + public CosmosAccessException(String msg) { super(msg); this.cosmosException = null; } @@ -36,7 +36,7 @@ public CosmosDBAccessException(String msg) { * @param msg the detail message * @param cause the nested Throwable */ - public CosmosDBAccessException(@Nullable String msg, @Nullable Throwable cause) { + public CosmosAccessException(@Nullable String msg, @Nullable Throwable cause) { super(msg, cause); if (cause instanceof CosmosException) { this.cosmosException = (CosmosException) cause; @@ -52,7 +52,7 @@ public CosmosDBAccessException(@Nullable String msg, @Nullable Throwable cause) * @param msg the detail message * @param cause the nested exception */ - public CosmosDBAccessException(@Nullable String msg, @Nullable Exception cause) { + public CosmosAccessException(@Nullable String msg, @Nullable Exception cause) { super(msg, cause); this.cosmosException = cause instanceof CosmosException ? (CosmosException) cause diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBExceptionUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtils.java similarity index 91% rename from sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBExceptionUtils.java rename to sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtils.java index 6c285ed160b0..98ce049271ca 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosDBExceptionUtils.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/exception/CosmosExceptionUtils.java @@ -10,7 +10,7 @@ /** * To handle and throw a cosmos db exception when access the database */ -public class CosmosDBExceptionUtils { +public class CosmosExceptionUtils { /** * To throw a CosmosDBAccessException @@ -19,7 +19,7 @@ public class CosmosDBExceptionUtils { * @param throwable exception * @param type class of Mono * @return Mono instance - * @throws CosmosDBAccessException for operations on cosmos db + * @throws CosmosAccessException for operations on cosmos db */ public static Mono exceptionHandler(String message, Throwable throwable) { if (StringUtils.isEmpty(message)) { @@ -27,7 +27,7 @@ public static Mono exceptionHandler(String message, Throwable throwable) } // Unwrap the exception in case if it is a reactive exception final Throwable unwrappedThrowable = Exceptions.unwrap(throwable); - throw new CosmosDBAccessException(message, unwrappedThrowable); + throw new CosmosAccessException(message, unwrappedThrowable); } /** diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleCosmosRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleCosmosRepository.java index f82a702575b6..0ea68ee18292 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleCosmosRepository.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/repository/support/SimpleCosmosRepository.java @@ -35,7 +35,7 @@ public class SimpleCosmosRepository implements Cosmo /** * Initialization * - * @param metadata for cosmos entity information + * @param metadata for cosmos entity information * @param applicationContext to get bean of CosmosOperations class */ public SimpleCosmosRepository(CosmosEntityInformation metadata, @@ -51,7 +51,7 @@ public SimpleCosmosRepository(CosmosEntityInformation metadata, /** * Initialization * - * @param metadata for cosmos entity information + * @param metadata for cosmos entity information * @param dbOperations for cosmosDB operation */ public SimpleCosmosRepository(CosmosEntityInformation metadata, @@ -72,7 +72,7 @@ private CosmosContainerProperties createContainerIfNotExists() { * save entity without partition * * @param entity to be saved - * @param type of entity + * @param type of entity * @return entity */ @Override @@ -101,7 +101,7 @@ private PartitionKey createKey(String partitionKeyValue) { * batch save entities * * @param entities Batch entities - * @param type of entities + * @param type of entities * @return return the saved entities */ @Override @@ -151,7 +151,7 @@ public Optional findById(ID id) { Assert.notNull(id, "id must not be null"); if (id instanceof String - && !StringUtils.hasText((String)id)) { + && !StringUtils.hasText((String) id)) { return Optional.empty(); } @@ -164,7 +164,7 @@ public Optional findById(ID id, PartitionKey partitionKey) { Assert.notNull(id, "id must not be null"); if (id instanceof String - && !StringUtils.hasText((String)id)) { + && !StringUtils.hasText((String) id)) { return Optional.empty(); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java index 720e707d0004..427066bdfdf4 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java @@ -9,7 +9,7 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.ResponseDiagnostics; import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories; @@ -25,32 +25,32 @@ public class AppConfiguration extends AbstractCosmosConfiguration { private static final Logger logger = LoggerFactory.getLogger(AppConfiguration.class); - @Value("${azure.cosmosdb.uri}") + @Value("${azure.cosmos.uri}") private String uri; - @Value("${azure.cosmosdb.key}") + @Value("${azure.cosmos.key}") private String key; - @Value("${azure.cosmosdb.secondaryKey}") + @Value("${azure.cosmos.secondaryKey}") private String secondaryKey; - @Value("${azure.cosmosdb.database}") + @Value("${azure.cosmos.database}") private String dbName; - @Value("${azure.cosmosdb.queryMetricsEnabled}") + @Value("${azure.cosmos.queryMetricsEnabled}") private boolean queryMetricsEnabled; private AzureKeyCredential azureKeyCredential; - public CosmosDBConfig getConfig() { + public CosmosConfig getConfig() { this.azureKeyCredential = new AzureKeyCredential(key); CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder().endpoint(uri).credential(azureKeyCredential); - return CosmosDBConfig.builder() - .database(dbName) - .enableQueryMetrics(queryMetricsEnabled) - .cosmosClientBuilder(cosmosClientBuilder) - .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) - .build(); + return CosmosConfig.builder() + .database(dbName) + .enableQueryMetrics(queryMetricsEnabled) + .cosmosClientBuilder(cosmosClientBuilder) + .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) + .build(); } public void switchToSecondaryKey() { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java index 155e5852586c..5780bcb251be 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java @@ -10,7 +10,7 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @@ -19,27 +19,27 @@ @EnableCosmosRepositories public class AppConfigurationCodeSnippet extends AbstractCosmosConfiguration { // configuration code - @Value("${azure.cosmosdb.uri}") + @Value("${azure.cosmos.uri}") private String uri; - @Value("${azure.cosmosdb.key}") + @Value("${azure.cosmos.key}") private String key; - @Value("${azure.cosmosdb.secondaryKey}") + @Value("${azure.cosmos.secondaryKey}") private String secondaryKey; - @Value("${azure.cosmosdb.database}") + @Value("${azure.cosmos.database}") private String dbName; - @Value("${azure.cosmosdb.queryMetricsEnabled}") + @Value("${azure.cosmos.queryMetricsEnabled}") private boolean queryMetricsEnabled; - public CosmosDBConfig getConfig() { + public CosmosConfig getConfig() { AzureKeyCredential azureKeyCredential = new AzureKeyCredential(key); - return CosmosDBConfig.builder() - .database(dbName) - .cosmosClientBuilder(new CosmosClientBuilder().credential(azureKeyCredential)) - .enableQueryMetrics(queryMetricsEnabled) - .build(); + return CosmosConfig.builder() + .database(dbName) + .cosmosClientBuilder(new CosmosClientBuilder().credential(azureKeyCredential)) + .enableQueryMetrics(queryMetricsEnabled) + .build(); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDBProperties.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosProperties.java similarity index 94% rename from sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDBProperties.java rename to sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosProperties.java index de52ce407c71..b073a18479a4 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosDBProperties.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosProperties.java @@ -9,8 +9,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties; -@ConfigurationProperties(prefix = "azure.cosmosdb") -public class CosmosDBProperties { +@ConfigurationProperties(prefix = "azure.cosmos") +public class CosmosProperties { private String uri; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java index 96de45a0acb7..727758ef6888 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java @@ -8,7 +8,7 @@ */ import com.azure.core.credential.AzureKeyCredential; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.ResponseDiagnostics; import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; import com.azure.spring.data.cosmos.repository.config.EnableReactiveCosmosRepositories; @@ -22,26 +22,26 @@ import org.springframework.lang.Nullable; @Configuration -@EnableConfigurationProperties(CosmosDBProperties.class) +@EnableConfigurationProperties(CosmosProperties.class) @EnableReactiveCosmosRepositories @PropertySource("classpath:application.properties") public class UserRepositoryConfiguration extends AbstractCosmosConfiguration { private static final Logger logger = LoggerFactory.getLogger(AppConfiguration.class); @Autowired - private CosmosDBProperties properties; + private CosmosProperties properties; private AzureKeyCredential azureKeyCredential; @Bean - public CosmosDBConfig cosmosDbConfig() { + public CosmosConfig cosmosConfig() { this.azureKeyCredential = new AzureKeyCredential(properties.getKey()); - return CosmosDBConfig.builder() - .database(properties.getDatabase()) - .cosmosClientBuilder(new CosmosClientBuilder().credential(azureKeyCredential)) - .enableQueryMetrics(properties.isQueryMetricsEnabled()) - .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) - .build(); + return CosmosConfig.builder() + .database(properties.getDatabase()) + .cosmosClientBuilder(new CosmosClientBuilder().credential(azureKeyCredential)) + .enableQueryMetrics(properties.isQueryMetricsEnabled()) + .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) + .build(); } public void switchToSecondaryKey() { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDBFactoryTestIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosFactoryTestIT.java similarity index 79% rename from sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDBFactoryTestIT.java rename to sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosFactoryTestIT.java index bcc9100d269a..0b33eb9bf9bf 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosDBFactoryTestIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosFactoryTestIT.java @@ -4,7 +4,7 @@ import com.azure.cosmos.CosmosClientBuilder; import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import org.apache.commons.lang3.reflect.FieldUtils; import org.junit.Test; @@ -19,56 +19,56 @@ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestRepositoryConfig.class) -public class CosmosDBFactoryTestIT { +public class CosmosFactoryTestIT { - @Value("${cosmosdb.uri:}") + @Value("${cosmos.uri:}") private String cosmosDbUri; - @Value("${cosmosdb.key:}") + @Value("${cosmos.key:}") private String cosmosDbKey; @Test(expected = IllegalArgumentException.class) public void testEmptyKey() { - final CosmosDBConfig dbConfig = CosmosDBConfig.builder() + final CosmosConfig cosmosConfig = CosmosConfig.builder() .database(TestConstants.DB_NAME) .cosmosClientBuilder(new CosmosClientBuilder() .endpoint(TestConstants.COSMOSDB_FAKE_HOST) .key("")) .build(); - new CosmosDBFactory(dbConfig).getCosmosSyncClient(); + new CosmosFactory(cosmosConfig).getCosmosSyncClient(); } @Test public void testInvalidEndpoint() { - final CosmosDBConfig dbConfig = CosmosDBConfig.builder() + final CosmosConfig cosmosConfig = CosmosConfig.builder() .database(TestConstants.DB_NAME) .cosmosClientBuilder(new CosmosClientBuilder() .endpoint(TestConstants.COSMOSDB_FAKE_HOST) .key(TestConstants.COSMOSDB_FAKE_KEY)) .build(); - final CosmosDBFactory factory = new CosmosDBFactory(dbConfig); + final CosmosFactory factory = new CosmosFactory(cosmosConfig); assertThat(factory).isNotNull(); } @Test public void testConnectionPolicyUserAgentKept() throws IllegalAccessException { - final CosmosDBConfig dbConfig = CosmosDBConfig.builder() + final CosmosConfig cosmosConfig = CosmosConfig.builder() .database(TestConstants.DB_NAME) .cosmosClientBuilder(new CosmosClientBuilder() .endpoint(cosmosDbUri) .key(cosmosDbKey)) .build(); - new CosmosDBFactory(dbConfig).getCosmosAsyncClient(); + new CosmosFactory(cosmosConfig).getCosmosAsyncClient(); - final String uaSuffix = getUserAgentSuffixValue(dbConfig.getCosmosClientBuilder()); + final String uaSuffix = getUserAgentSuffixValue(cosmosConfig.getCosmosClientBuilder()); assertThat(uaSuffix).contains("spring-data"); } private String getUserAgentSuffixValue(CosmosClientBuilder cosmosClientBuilder) throws IllegalAccessException { final Field userAgentSuffix = FieldUtils.getDeclaredField(CosmosClientBuilder.class, "userAgentSuffix", true); - return (String)userAgentSuffix.get(cosmosClientBuilder); + return (String) userAgentSuffix.get(cosmosClientBuilder); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfigurationIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfigurationIT.java index b4fac37b0ba8..77fc5dc99785 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfigurationIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/config/AbstractCosmosConfigurationIT.java @@ -7,7 +7,7 @@ import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.CosmosClientBuilder; import com.azure.spring.data.cosmos.Constants; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.common.ExpressionResolver; import com.azure.spring.data.cosmos.common.TestConstants; import com.fasterxml.jackson.databind.ObjectMapper; @@ -38,7 +38,7 @@ public class AbstractCosmosConfigurationIT { @Test public void containsExpressionResolver() { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( - TestCosmosConfiguration.class); + TestCosmosConfiguration.class); assertNotNull(context.getBean(ExpressionResolver.class)); } @@ -46,15 +46,15 @@ public void containsExpressionResolver() { @Test public void containsCosmosDbFactory() { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( - TestCosmosConfiguration.class); + TestCosmosConfiguration.class); - Assertions.assertThat(context.getBean(CosmosDBFactory.class)).isNotNull(); + Assertions.assertThat(context.getBean(CosmosFactory.class)).isNotNull(); } @Test(expected = NoSuchBeanDefinitionException.class) public void defaultObjectMapperBeanNotExists() { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( - TestCosmosConfiguration.class); + TestCosmosConfiguration.class); context.getBean(ObjectMapper.class); } @@ -62,7 +62,7 @@ public void defaultObjectMapperBeanNotExists() { @Test public void objectMapperIsConfigurable() { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( - ObjectMapperConfiguration.class); + ObjectMapperConfiguration.class); Assertions.assertThat(context.getBean(ObjectMapper.class)).isNotNull(); Assertions.assertThat(context.getBean(Constants.OBJECT_MAPPER_BEAN_NAME)).isNotNull(); @@ -71,8 +71,8 @@ public void objectMapperIsConfigurable() { @Test public void testCosmosClientBuilderConfigurable() throws IllegalAccessException { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( - RequestOptionsConfiguration.class); - final CosmosDBFactory factory = context.getBean(CosmosDBFactory.class); + RequestOptionsConfiguration.class); + final CosmosFactory factory = context.getBean(CosmosFactory.class); Assertions.assertThat(factory).isNotNull(); @@ -82,18 +82,18 @@ public void testCosmosClientBuilderConfigurable() throws IllegalAccessException final Field consistencyLevelField = FieldUtils.getDeclaredField(CosmosClientBuilder.class, "desiredConsistencyLevel", true); ConsistencyLevel consistencyLevel = - (ConsistencyLevel)consistencyLevelField.get(cosmosClientBuilder); + (ConsistencyLevel) consistencyLevelField.get(cosmosClientBuilder); Assertions.assertThat(consistencyLevel).isEqualTo(ConsistencyLevel.CONSISTENT_PREFIX); } @Configuration - @PropertySource(value = {"classpath:application.properties"}) + @PropertySource(value = { "classpath:application.properties" }) static class TestCosmosConfiguration extends AbstractCosmosConfiguration { - @Value("${cosmosdb.uri:}") + @Value("${cosmos.uri:}") private String cosmosDbUri; - @Value("${cosmosdb.key:}") + @Value("${cosmos.key:}") private String cosmosDbKey; @Value("${cosmosdb.database:}") @@ -103,18 +103,18 @@ static class TestCosmosConfiguration extends AbstractCosmosConfiguration { private CosmosAsyncClient mockClient; @Bean - public CosmosDBConfig getConfig() { + public CosmosConfig getConfig() { final String dbName = StringUtils.hasText(this.database) ? this.database : TestConstants.DB_NAME; - return CosmosDBConfig.builder() - .cosmosClientBuilder(new CosmosClientBuilder() - .endpoint(cosmosDbUri) - .key(cosmosDbKey)) - .database(dbName) - .build(); + return CosmosConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(cosmosDbUri) + .key(cosmosDbKey)) + .database(dbName) + .build(); } @Override - public CosmosAsyncClient cosmosAsyncClient(CosmosDBFactory cosmosDBFactory) { + public CosmosAsyncClient cosmosAsyncClient(CosmosFactory cosmosFactory) { return mockClient; } } @@ -128,29 +128,29 @@ public ObjectMapper objectMapper() { } @Configuration - @PropertySource(value = {"classpath:application.properties"}) + @PropertySource(value = { "classpath:application.properties" }) static class RequestOptionsConfiguration extends AbstractCosmosConfiguration { - @Value("${cosmosdb.uri:}") + @Value("${cosmos.uri:}") private String cosmosDbUri; - @Value("${cosmosdb.key:}") + @Value("${cosmos.key:}") private String cosmosDbKey; @Value("${cosmosdb.database:}") private String database; @Bean - public CosmosDBConfig getConfig() { + public CosmosConfig getConfig() { final String dbName = StringUtils.hasText(this.database) ? this.database : TestConstants.DB_NAME; final CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() .key(cosmosDbKey) .endpoint(cosmosDbUri) .consistencyLevel(ConsistencyLevel.CONSISTENT_PREFIX); - return CosmosDBConfig.builder() - .database(dbName) - .cosmosClientBuilder(cosmosClientBuilder) - .build(); + return CosmosConfig.builder() + .database(dbName) + .cosmosClientBuilder(cosmosClientBuilder) + .build(); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIT.java index fe682ce56d21..c8c3c5fff883 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateIT.java @@ -4,10 +4,10 @@ import com.azure.cosmos.CosmosException; import com.azure.cosmos.models.PartitionKey; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.common.PageTestUtils; import com.azure.spring.data.cosmos.common.ResponseDiagnosticsTestUtils; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; @@ -15,7 +15,7 @@ import com.azure.spring.data.cosmos.core.query.CriteriaType; import com.azure.spring.data.cosmos.core.query.DocumentQuery; import com.azure.spring.data.cosmos.domain.Person; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; +import com.azure.spring.data.cosmos.exception.CosmosAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.assertj.core.util.Lists; @@ -85,14 +85,14 @@ public class CosmosTemplateIT { @Autowired private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; @Autowired private ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils; @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - final CosmosDBFactory cosmosDbFactory = new CosmosDBFactory(dbConfig); + final CosmosFactory cosmosFactory = new CosmosFactory(cosmosConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = new CosmosEntityInformation<>(Person.class); @@ -102,7 +102,7 @@ public void setUp() throws ClassNotFoundException { final MappingCosmosConverter cosmosConverter = new MappingCosmosConverter(mappingContext, null); - cosmosTemplate = new CosmosTemplate(cosmosDbFactory, cosmosConverter, dbConfig.getDatabase()); + cosmosTemplate = new CosmosTemplate(cosmosFactory, cosmosConverter, cosmosConfig.getDatabase()); cosmosTemplate.createContainerIfNotExists(personInfo); initialized = true; } @@ -120,7 +120,7 @@ public static void afterClassCleanup() { cosmosTemplate.deleteContainer(personInfo.getContainerName()); } - @Test(expected = CosmosDBAccessException.class) + @Test(expected = CosmosAccessException.class) public void testInsertDuplicateId() { cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); @@ -226,7 +226,7 @@ public void testOptimisticLockWhenUpdatingWithWrongEtag() { try { cosmosTemplate.upsert(Person.class.getSimpleName(), updated); - } catch (CosmosDBAccessException e) { + } catch (CosmosAccessException e) { assertThat(e.getCosmosException()).isNotNull(); final Throwable cosmosClientException = e.getCosmosException(); assertThat(cosmosClientException).isInstanceOf(CosmosException.class); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplatePartitionIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplatePartitionIT.java index 69652c1f6883..487cdafaa0e8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplatePartitionIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplatePartitionIT.java @@ -4,9 +4,9 @@ package com.azure.spring.data.cosmos.core; import com.azure.cosmos.models.PartitionKey; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.common.PageTestUtils; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; @@ -69,12 +69,12 @@ public class CosmosTemplatePartitionIT { @Autowired private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - final CosmosDBFactory cosmosDbFactory = new CosmosDBFactory(dbConfig); + final CosmosFactory cosmosFactory = new CosmosFactory(cosmosConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = new CosmosEntityInformation<>(PartitionPerson.class); @@ -82,7 +82,7 @@ public void setUp() throws ClassNotFoundException { final MappingCosmosConverter dbConverter = new MappingCosmosConverter(mappingContext, null); - cosmosTemplate = new CosmosTemplate(cosmosDbFactory, dbConverter, dbConfig.getDatabase()); + cosmosTemplate = new CosmosTemplate(cosmosFactory, dbConverter, cosmosConfig.getDatabase()); containerName = personInfo.getContainerName(); cosmosTemplate.createContainerIfNotExists(personInfo); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateUnitTest.java index 9ab3d7a72c0d..8b85701646f8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/CosmosTemplateUnitTest.java @@ -4,9 +4,9 @@ package com.azure.spring.data.cosmos.core; import com.azure.cosmos.CosmosClientBuilder; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; @@ -16,14 +16,14 @@ public class CosmosTemplateUnitTest { @Test(expected = IllegalArgumentException.class) public void rejectNullDbFactory() { - final CosmosDBConfig dbConfig = CosmosDBConfig.builder() - .cosmosClientBuilder(new CosmosClientBuilder() + final CosmosConfig cosmosConfig = CosmosConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() .endpoint("") .key("")) - .database(TestConstants.DB_NAME) - .build(); - final CosmosDBFactory cosmosDbFactory = new CosmosDBFactory(dbConfig); + .database(TestConstants.DB_NAME) + .build(); + final CosmosFactory cosmosFactory = new CosmosFactory(cosmosConfig); - new CosmosTemplate(cosmosDbFactory, null, TestConstants.DB_NAME); + new CosmosTemplate(cosmosFactory, null, TestConstants.DB_NAME); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java index 21d52a95301e..c476de0f39d0 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplateIT.java @@ -5,17 +5,17 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.cosmos.CosmosException; import com.azure.cosmos.models.PartitionKey; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.common.ResponseDiagnosticsTestUtils; import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; import com.azure.spring.data.cosmos.core.query.Criteria; import com.azure.spring.data.cosmos.core.query.CriteriaType; import com.azure.spring.data.cosmos.core.query.DocumentQuery; import com.azure.spring.data.cosmos.domain.Person; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; +import com.azure.spring.data.cosmos.exception.CosmosAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; import org.assertj.core.api.Assertions; @@ -38,7 +38,7 @@ import reactor.test.StepVerifier; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -67,10 +67,10 @@ public class ReactiveCosmosTemplateIT { private static final String PRECONDITION_IS_NOT_MET = "is not met"; private static final String WRONG_ETAG = "WRONG_ETAG"; - @Value("${cosmosdb.secondaryKey}") + @Value("${cosmos.secondaryKey}") private String cosmosDbSecondaryKey; - @Value("${cosmosdb.key}") + @Value("${cosmos.key}") private String cosmosDbKey; private static ReactiveCosmosTemplate cosmosTemplate; @@ -85,7 +85,7 @@ public class ReactiveCosmosTemplateIT { @Autowired private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; @Autowired private ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils; @@ -93,8 +93,8 @@ public class ReactiveCosmosTemplateIT { public void setUp() throws ClassNotFoundException { if (!initialized) { azureKeyCredential = new AzureKeyCredential(cosmosDbKey); - dbConfig.getCosmosClientBuilder().credential(azureKeyCredential); - final CosmosDBFactory dbFactory = new CosmosDBFactory(dbConfig); + cosmosConfig.getCosmosClientBuilder().credential(azureKeyCredential); + final CosmosFactory dbFactory = new CosmosFactory(cosmosConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = new CosmosEntityInformation<>(Person.class); @@ -105,7 +105,7 @@ public void setUp() throws ClassNotFoundException { final MappingCosmosConverter dbConverter = new MappingCosmosConverter(mappingContext, null); cosmosTemplate = new ReactiveCosmosTemplate(dbFactory, dbConverter, - dbConfig.getDatabase()); + cosmosConfig.getDatabase()); cosmosTemplate.createContainerIfNotExists(personInfo).block(); initialized = true; } @@ -131,7 +131,7 @@ public void testInsertDuplicateId() { final Mono insertMono = cosmosTemplate.insert(TEST_PERSON, new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON))); StepVerifier.create(insertMono) - .expectError(CosmosDBAccessException.class) + .expectError(CosmosAccessException.class) .verify(); } @@ -245,9 +245,9 @@ public void testOptimisticLockWhenUpdatingWithWrongEtag() { try { cosmosTemplate.upsert(updated).block(); - } catch (CosmosDBAccessException cosmosDbAccessException) { - assertThat(cosmosDbAccessException.getCosmosException()).isNotNull(); - final Throwable cosmosClientException = cosmosDbAccessException.getCosmosException(); + } catch (CosmosAccessException cosmosAccessException) { + assertThat(cosmosAccessException.getCosmosException()).isNotNull(); + final Throwable cosmosClientException = cosmosAccessException.getCosmosException(); assertThat(cosmosClientException).isInstanceOf(CosmosException.class); assertThat(cosmosClientException.getMessage()).contains(PRECONDITION_IS_NOT_MET); @@ -343,7 +343,7 @@ public void testDeleteByIdBySecondaryKey() { @Test public void testFind() { final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", - Arrays.asList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); + Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final DocumentQuery query = new DocumentQuery(criteria); final Flux personFlux = cosmosTemplate.find(query, Person.class, Person.class.getSimpleName()); @@ -351,7 +351,7 @@ public void testFind() { // add ignore testing final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", - Arrays.asList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); + Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); final DocumentQuery queryIgnoreCase = new DocumentQuery(criteriaIgnoreCase); final Flux personFluxIgnoreCase = cosmosTemplate.find(queryIgnoreCase, Person.class, Person.class.getSimpleName()); @@ -365,14 +365,14 @@ public void testFind() { @Test public void testExists() { final Criteria criteria = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", - Arrays.asList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); + Collections.singletonList(TEST_PERSON.getFirstName()), Part.IgnoreCaseType.NEVER); final DocumentQuery query = new DocumentQuery(criteria); final Mono exists = cosmosTemplate.exists(query, Person.class, containerName); StepVerifier.create(exists).expectNext(true).verifyComplete(); // add ignore testing final Criteria criteriaIgnoreCase = Criteria.getInstance(CriteriaType.IS_EQUAL, "firstName", - Arrays.asList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); + Collections.singletonList(TEST_PERSON.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); final DocumentQuery queryIgnoreCase = new DocumentQuery(criteriaIgnoreCase); final Mono existsIgnoreCase = cosmosTemplate.exists(queryIgnoreCase, Person.class, containerName); StepVerifier.create(existsIgnoreCase).expectNext(true).verifyComplete(); @@ -385,7 +385,7 @@ public void testExists() { @Test public void testCount() { final Mono count = cosmosTemplate.count(containerName); - StepVerifier.create(count).expectNext((long)1).verifyComplete(); + StepVerifier.create(count).expectNext((long) 1).verifyComplete(); assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); Assertions.assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); @@ -396,7 +396,7 @@ public void testCount() { public void testCountBySecondaryKey() { azureKeyCredential.update(cosmosDbSecondaryKey); final Mono count = cosmosTemplate.count(containerName); - StepVerifier.create(count).expectNext((long)1).verifyComplete(); + StepVerifier.create(count).expectNext((long) 1).verifyComplete(); } @Test @@ -406,7 +406,7 @@ public void testInvalidSecondaryKey() { TEST_PERSON.getId(), Person.class); StepVerifier.create(findById) - .expectError(CosmosDBAccessException.class) + .expectError(CosmosAccessException.class) .verify(); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplatePartitionIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplatePartitionIT.java index d0b6ccef1b50..eda513baf86c 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplatePartitionIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/ReactiveCosmosTemplatePartitionIT.java @@ -3,9 +3,9 @@ package com.azure.spring.data.cosmos.core; import com.azure.cosmos.models.PartitionKey; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; import com.azure.spring.data.cosmos.core.query.Criteria; @@ -56,12 +56,12 @@ public class ReactiveCosmosTemplatePartitionIT { @Autowired private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - final CosmosDBFactory dbFactory = new CosmosDBFactory(dbConfig); + final CosmosFactory dbFactory = new CosmosFactory(cosmosConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = @@ -72,7 +72,7 @@ public void setUp() throws ClassNotFoundException { final MappingCosmosConverter dbConverter = new MappingCosmosConverter(mappingContext, null); - cosmosTemplate = new ReactiveCosmosTemplate(dbFactory, dbConverter, dbConfig.getDatabase()); + cosmosTemplate = new ReactiveCosmosTemplate(dbFactory, dbConverter, cosmosConfig.getDatabase()); cosmosTemplate.createContainerIfNotExists(personInfo).block(); initialized = true; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/convert/ZonedDateTimeDeserializerTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/convert/ZonedDateTimeDeserializerTest.java index 64e3478866ba..88b593f2fe95 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/convert/ZonedDateTimeDeserializerTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/convert/ZonedDateTimeDeserializerTest.java @@ -9,7 +9,7 @@ import java.time.ZonedDateTime; import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class ZonedDateTimeDeserializerTest { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerfConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerfConfiguration.java index 1e71ad3ab5a9..3bb9359ec445 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerfConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/PerfConfiguration.java @@ -4,7 +4,7 @@ import com.azure.cosmos.CosmosClientBuilder; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.performance.utils.Constants; import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories; import org.springframework.beans.factory.annotation.Value; @@ -23,12 +23,12 @@ public class PerfConfiguration extends AbstractCosmosConfiguration { private String cosmosDbKey; @Bean - public CosmosDBConfig getConfig() { - return CosmosDBConfig.builder() - .cosmosClientBuilder(new CosmosClientBuilder() + public CosmosConfig getConfig() { + return CosmosConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() .endpoint(cosmosDbUri) .key(cosmosDbKey)) - .database(Constants.PERF_DATABASE_NAME) - .build(); + .database(Constants.PERF_DATABASE_NAME) + .build(); } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/service/SdkService.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/service/SdkService.java index cac5122123ba..5cd8706cc51c 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/service/SdkService.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/performance/service/SdkService.java @@ -105,10 +105,10 @@ public List findAllById(Iterable ids) { final Iterator> feedResponseIterator = cosmosClient.getDatabase(dbName) - .getContainer(containerName) - .queryItems(sql, new CosmosQueryRequestOptions(), PerfPerson.class) - .iterableByPage() - .iterator(); + .getContainer(containerName) + .queryItems(sql, new CosmosQueryRequestOptions(), PerfPerson.class) + .iterableByPage() + .iterator(); while (feedResponseIterator.hasNext()) { final FeedResponse next = feedResponseIterator.next(); docs.addAll(next.getResults()); @@ -172,12 +172,10 @@ public long count() { final String sql = "SELECT VALUE COUNT(1) FROM " + containerName; final Iterator> feedResponseIterator = cosmosClient.getDatabase(dbName) - .getContainer(containerName) - .queryItems(sql - , - new CosmosQueryRequestOptions(), JsonNode.class) - .iterableByPage() - .iterator(); + .getContainer(containerName) + .queryItems(sql, new CosmosQueryRequestOptions(), JsonNode.class) + .iterableByPage() + .iterator(); return feedResponseIterator.next().getResults().get(0).get("_aggregate").asLong(); } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/TestRepositoryConfig.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/TestRepositoryConfig.java index d4289436ee61..0fa81fed704f 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/TestRepositoryConfig.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/TestRepositoryConfig.java @@ -7,7 +7,7 @@ import com.azure.spring.data.cosmos.common.ResponseDiagnosticsTestUtils; import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories; import com.azure.spring.data.cosmos.repository.config.EnableReactiveCosmosRepositories; import org.springframework.beans.factory.annotation.Value; @@ -21,16 +21,16 @@ @EnableCosmosRepositories @EnableReactiveCosmosRepositories public class TestRepositoryConfig extends AbstractCosmosConfiguration { - @Value("${cosmosdb.uri:}") + @Value("${cosmos.uri:}") private String cosmosDbUri; - @Value("${cosmosdb.key:}") + @Value("${cosmos.key:}") private String cosmosDbKey; - @Value("${cosmosdb.database:}") + @Value("${cosmos.database:}") private String database; - @Value("${cosmosdb.queryMetricsEnabled}") + @Value("${cosmos.queryMetricsEnabled}") private boolean queryMetricsEnabled; @Bean @@ -39,18 +39,17 @@ public ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils() { } @Bean - public CosmosDBConfig getConfig() { - final String dbName = StringUtils.hasText(this.database) ? this.database : - TestConstants.DB_NAME; - return CosmosDBConfig.builder() - .cosmosClientBuilder(new CosmosClientBuilder() - .key(cosmosDbKey) - .endpoint(cosmosDbUri) - .contentResponseOnWriteEnabled(true)) - .database(dbName) - .enableQueryMetrics(queryMetricsEnabled) - .responseDiagnosticsProcessor(responseDiagnosticsTestUtils().getResponseDiagnosticsProcessor()) - .build(); + public CosmosConfig getConfig() { + final String dbName = StringUtils.hasText(this.database) ? this.database : TestConstants.DB_NAME; + return CosmosConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .key(cosmosDbKey) + .endpoint(cosmosDbUri) + .contentResponseOnWriteEnabled(true)) + .database(dbName) + .enableQueryMetrics(queryMetricsEnabled) + .responseDiagnosticsProcessor(responseDiagnosticsTestUtils().getResponseDiagnosticsProcessor()) + .build(); } @Bean diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/config/CosmosRepositoryConfigurationExtensionUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/config/CosmosRepositoryConfigurationExtensionUnitTest.java index 440cc1d93be9..73945c6eeee2 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/config/CosmosRepositoryConfigurationExtensionUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/config/CosmosRepositoryConfigurationExtensionUnitTest.java @@ -10,7 +10,7 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.type.StandardAnnotationMetadata; +import org.springframework.core.type.AnnotationMetadata; import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource; import org.springframework.data.repository.config.RepositoryConfiguration; import org.springframework.data.repository.config.RepositoryConfigurationSource; @@ -21,11 +21,11 @@ public class CosmosRepositoryConfigurationExtensionUnitTest { - StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(Config.class, true); + AnnotationMetadata metadata = AnnotationMetadata.introspect(Config.class); ResourceLoader loader = new PathMatchingResourcePatternResolver(); Environment environment = new StandardEnvironment(); RepositoryConfigurationSource configurationSource = new AnnotationRepositoryConfigurationSource(metadata, - EnableCosmosRepositories.class, loader, environment, new DefaultListableBeanFactory()); + EnableCosmosRepositories.class, loader, environment, new DefaultListableBeanFactory(), null); private static void assertHashRepo(Class repositoryInterface, Collection> configs) { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/config/ReactiveCosmosRepositoryConfigurationExtensionUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/config/ReactiveCosmosRepositoryConfigurationExtensionUnitTest.java index 30b78a63900e..57e518e03ef6 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/config/ReactiveCosmosRepositoryConfigurationExtensionUnitTest.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/config/ReactiveCosmosRepositoryConfigurationExtensionUnitTest.java @@ -10,7 +10,7 @@ import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.core.type.StandardAnnotationMetadata; +import org.springframework.core.type.AnnotationMetadata; import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource; import org.springframework.data.repository.config.RepositoryConfiguration; import org.springframework.data.repository.config.RepositoryConfigurationSource; @@ -21,11 +21,11 @@ public class ReactiveCosmosRepositoryConfigurationExtensionUnitTest { - StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(Config.class, true); + AnnotationMetadata metadata = AnnotationMetadata.introspect(Config.class); ResourceLoader loader = new PathMatchingResourcePatternResolver(); Environment environment = new StandardEnvironment(); RepositoryConfigurationSource configurationSource = new AnnotationRepositoryConfigurationSource(metadata, - EnableReactiveCosmosRepositories.class, loader, environment, new DefaultListableBeanFactory()); + EnableReactiveCosmosRepositories.class, loader, environment, new DefaultListableBeanFactory(), null); private static void assertHashRepo(Class repositoryInterface, Collection> configs) { diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CosmosAnnotationIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CosmosAnnotationIT.java index f408825467ff..40fb7e95f3b1 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CosmosAnnotationIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/CosmosAnnotationIT.java @@ -4,10 +4,10 @@ import com.azure.cosmos.models.CosmosContainerProperties; import com.azure.cosmos.models.IndexingPolicy; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.common.TestUtils; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.mapping.CosmosMappingContext; @@ -39,7 +39,7 @@ public class CosmosAnnotationIT { @Autowired private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; private static CosmosTemplate cosmosTemplate; private static CosmosContainerProperties collectionRole; @@ -52,7 +52,7 @@ public class CosmosAnnotationIT { @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - final CosmosDBFactory cosmosDbFactory = new CosmosDBFactory(dbConfig); + final CosmosFactory cosmosFactory = new CosmosFactory(cosmosConfig); roleInfo = new CosmosEntityInformation<>(Role.class); sampleInfo = new CosmosEntityInformation<>(TimeToLiveSample.class); @@ -62,7 +62,7 @@ public void setUp() throws ClassNotFoundException { final MappingCosmosConverter mappingConverter = new MappingCosmosConverter(dbContext, null); - cosmosTemplate = new CosmosTemplate(cosmosDbFactory, mappingConverter, dbConfig.getDatabase()); + cosmosTemplate = new CosmosTemplate(cosmosFactory, mappingConverter, cosmosConfig.getDatabase()); initialized = true; } collectionRole = cosmosTemplate.createContainerIfNotExists(roleInfo); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/IntegerIdDomainRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/IntegerIdDomainRepositoryIT.java index fe786a4d2054..f19eaa83834e 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/IntegerIdDomainRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/IntegerIdDomainRepositoryIT.java @@ -5,7 +5,7 @@ import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; import com.azure.spring.data.cosmos.domain.IntegerIdDomain; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; +import com.azure.spring.data.cosmos.exception.CosmosAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.IntegerIdDomainRepository; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; @@ -141,7 +141,7 @@ public void testDeleteById() { Assert.assertEquals(0, this.repository.count()); } - @Test(expected = CosmosDBAccessException.class) + @Test(expected = CosmosAccessException.class) public void testDeleteByIdShouldFailIfNothingToDelete() { this.repository.deleteAll(); this.repository.deleteById(DOMAIN.getNumber()); @@ -154,7 +154,7 @@ public void testDelete() { Assert.assertEquals(0, this.repository.count()); } - @Test(expected = CosmosDBAccessException.class) + @Test(expected = CosmosAccessException.class) public void testDeleteShouldFailIfNothingToDelete() { this.repository.deleteAll(); this.repository.delete(DOMAIN); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/MemoRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/MemoRepositoryIT.java index e8919bcea0ea..eda4c1579c59 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/MemoRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/MemoRepositoryIT.java @@ -7,7 +7,7 @@ import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.domain.Importance; import com.azure.spring.data.cosmos.domain.Memo; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; +import com.azure.spring.data.cosmos.exception.CosmosAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.MemoRepository; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; @@ -246,7 +246,7 @@ private void assertMemoListEquals(List memos, List reference) { Assert.assertEquals(reference, memos); } - @Test(expected = CosmosDBAccessException.class) + @Test(expected = CosmosAccessException.class) @Ignore // TODO(pan): Ignore this test case for now, will update this from service update. public void testFindByStartsWithWithException() { repository.findByMessageStartsWith(testMemo1.getMessage()); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java index 18f096b88f0f..5361cee83e5d 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java @@ -7,7 +7,7 @@ import com.azure.cosmos.models.FeedResponse; import com.azure.spring.data.cosmos.common.TestConstants; import com.azure.spring.data.cosmos.common.TestUtils; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; import com.azure.spring.data.cosmos.domain.PageableAddress; @@ -64,7 +64,7 @@ public class PageableAddressRepositoryIT { private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; @Before public void setUp() { @@ -173,7 +173,7 @@ public void testOffsetAndLimit() { final CosmosAsyncClient cosmosClient = applicationContext.getBean(CosmosAsyncClient.class); final Flux> feedResponseFlux = - cosmosClient.getDatabase(dbConfig.getDatabase()) + cosmosClient.getDatabase(cosmosConfig.getDatabase()) .getContainer(entityInformation.getContainerName()) .queryItems(query, options, PageableAddress.class) .byPage(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableMemoRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableMemoRepositoryIT.java index 528cf0ab0445..4998508bee5b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableMemoRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableMemoRepositoryIT.java @@ -5,7 +5,7 @@ import com.azure.cosmos.CosmosAsyncClient; import com.azure.cosmos.models.CosmosQueryRequestOptions; import com.azure.cosmos.models.FeedResponse; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; import com.azure.spring.data.cosmos.domain.Importance; @@ -57,7 +57,7 @@ public class PageableMemoRepositoryIT { private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; private static Set memoSet; @@ -138,7 +138,7 @@ private Flux> getItemsWithOffsetAndLimit(int skipCoun final String query = "SELECT * from c OFFSET " + skipCount + " LIMIT " + takeCount; final CosmosAsyncClient cosmosClient = applicationContext.getBean(CosmosAsyncClient.class); - return cosmosClient.getDatabase(dbConfig.getDatabase()) + return cosmosClient.getDatabase(cosmosConfig.getDatabase()) .getContainer(entityInformation.getContainerName()) .queryItems(query, options, PageableMemo.class) .byPage(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositorySortIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositorySortIT.java index fc05c600c160..d75df0779a2f 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositorySortIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ProjectRepositorySortIT.java @@ -5,7 +5,7 @@ import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.query.CosmosPageRequest; import com.azure.spring.data.cosmos.domain.SortedProject; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; +import com.azure.spring.data.cosmos.exception.CosmosAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.SortedProjectRepository; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; @@ -145,7 +145,7 @@ public void testFindAllUnSorted() { Assert.assertEquals(PROJECTS, projects); } - @Test(expected = CosmosDBAccessException.class) + @Test(expected = CosmosAccessException.class) public void testFindAllSortMoreThanOneOrderException() { final Sort sort = Sort.by(Sort.Direction.ASC, "name", "creator"); @@ -160,7 +160,7 @@ public void testFindAllSortIgnoreCaseException() { this.repository.findAll(sort); } - @Test(expected = CosmosDBAccessException.class) + @Test(expected = CosmosAccessException.class) public void testFindAllSortMissMatchException() { final Sort sort = Sort.by(Sort.Direction.ASC, "fake-name"); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveCourseRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveCourseRepositoryIT.java index bce8e441fd9c..afa98e5f4b69 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveCourseRepositoryIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/ReactiveCourseRepositoryIT.java @@ -5,7 +5,7 @@ import com.azure.cosmos.models.PartitionKey; import com.azure.spring.data.cosmos.core.ReactiveCosmosTemplate; import com.azure.spring.data.cosmos.domain.Course; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; +import com.azure.spring.data.cosmos.exception.CosmosAccessException; import com.azure.spring.data.cosmos.repository.TestRepositoryConfig; import com.azure.spring.data.cosmos.repository.repository.ReactiveCourseRepository; import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation; @@ -151,7 +151,7 @@ public void testUpsert() { @Test public void testDeleteByIdWithoutPartitionKey() { final Mono deleteMono = repository.deleteById(COURSE_1.getCourseId()); - StepVerifier.create(deleteMono).expectError(CosmosDBAccessException.class).verify(); + StepVerifier.create(deleteMono).expectError(CosmosAccessException.class).verify(); } @Test @@ -179,13 +179,13 @@ public void testDeleteByEntity() { @Test public void testDeleteByIdNotFound() { final Mono deleteMono = repository.deleteById(COURSE_ID_5); - StepVerifier.create(deleteMono).expectError(CosmosDBAccessException.class).verify(); + StepVerifier.create(deleteMono).expectError(CosmosAccessException.class).verify(); } @Test public void testDeleteByEntityNotFound() { final Mono deleteMono = repository.delete(COURSE_5); - StepVerifier.create(deleteMono).expectError(CosmosDBAccessException.class).verify(); + StepVerifier.create(deleteMono).expectError(CosmosAccessException.class).verify(); } @Test diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosDBAnnotationIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosAnnotationIT.java similarity index 88% rename from sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosDBAnnotationIT.java rename to sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosAnnotationIT.java index 02ec72cb3d2c..bf2300cc0f2b 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosDBAnnotationIT.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/SpELCosmosAnnotationIT.java @@ -3,9 +3,9 @@ package com.azure.spring.data.cosmos.repository.integration; import com.azure.cosmos.CosmosClientBuilder; -import com.azure.spring.data.cosmos.CosmosDBFactory; +import com.azure.spring.data.cosmos.CosmosFactory; import com.azure.spring.data.cosmos.common.TestConstants; -import com.azure.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.CosmosTemplate; import com.azure.spring.data.cosmos.core.convert.MappingCosmosConverter; import com.azure.spring.data.cosmos.core.convert.ObjectMapperFactory; @@ -32,15 +32,15 @@ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestRepositoryConfig.class) -public class SpELCosmosDBAnnotationIT { +public class SpELCosmosAnnotationIT { private static final SpELPropertyStudent TEST_PROPERTY_STUDENT = new SpELPropertyStudent(TestConstants.ID_1, TestConstants.FIRST_NAME, TestConstants.LAST_NAME); - @Value("${cosmosdb.uri}") + @Value("${cosmos.uri}") private String dbUri; - @Value("${cosmosdb.key}") + @Value("${cosmos.key}") private String dbKey; @Autowired @@ -84,13 +84,13 @@ public void testDynamicContainerNameWithBeanExpression() { @Test public void testDatabaseOperationsOnDynamicallyNamedCollection() throws ClassNotFoundException { - final CosmosDBConfig dbConfig = CosmosDBConfig.builder() - .cosmosClientBuilder(new CosmosClientBuilder() + final CosmosConfig cosmosConfig = CosmosConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() .endpoint(dbUri) .key(dbKey)) - .database(TestConstants.DB_NAME) - .build(); - final CosmosDBFactory dbFactory = new CosmosDBFactory(dbConfig); + .database(TestConstants.DB_NAME) + .build(); + final CosmosFactory dbFactory = new CosmosFactory(cosmosConfig); cosmosEntityInformation = new CosmosEntityInformation<>(SpELPropertyStudent.class); final CosmosMappingContext dbContext = new CosmosMappingContext(); diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/test/resources/application.properties b/sdk/cosmos/azure-spring-data-cosmos/src/test/resources/application.properties index 37e5a71beb70..5f47ae7f03be 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/test/resources/application.properties +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/resources/application.properties @@ -1,6 +1,6 @@ -cosmosdb.uri=${ACCOUNT_HOST} -cosmosdb.key=${ACCOUNT_KEY} -cosmosdb.secondaryKey=${SECONDARY_ACCOUNT_KEY} +cosmos.uri=${ACCOUNT_HOST} +cosmos.key=${ACCOUNT_KEY} +cosmos.secondaryKey=${SECONDARY_ACCOUNT_KEY} dynamic.collection.name=spel-property-collection # Performance test configurations @@ -9,4 +9,4 @@ perf.batch.size=3 perf.acceptance.percentage=10 # Populate query metrics -cosmosdb.queryMetricsEnabled=true +cosmos.queryMetricsEnabled=true From a68586a4e8fad1b8be88932c8aad06b7132319c1 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 16 Jul 2020 13:31:13 -0700 Subject: [PATCH 4/6] Fixed readme and code snippets --- sdk/cosmos/azure-spring-data-cosmos/README.md | 90 +++++++++++-------- .../azure/spring/data/cosmos/Constants.java | 2 +- .../com/azure/cosmos/AppConfiguration.java | 7 +- .../cosmos/AppConfigurationCodeSnippet.java | 25 +++++- .../ObjectMapperConfigurationCodeSnippet.java | 2 +- .../samples/java/com/azure/cosmos/User.java | 2 +- .../java/com/azure/cosmos/UserSample.java | 2 +- 7 files changed, 86 insertions(+), 44 deletions(-) diff --git a/sdk/cosmos/azure-spring-data-cosmos/README.md b/sdk/cosmos/azure-spring-data-cosmos/README.md index bcbcf71c8dc3..285258598fb5 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/README.md +++ b/sdk/cosmos/azure-spring-data-cosmos/README.md @@ -11,7 +11,6 @@ * [Spring data version support](#spring-data-version-support) * [Feature List](#feature-list) * [Quick Start](#quick-start) -* [Query Partitioned Collection](QueryPartitionedCollection.md) * [Beta version package](#Beta version package) * [Troubleshooting](#Troubleshooting) * [Contributing](#Contributing) @@ -34,14 +33,14 @@ Please refer to [sample project here](./samplecode). There're 2 ways to map a field in domain class to `id` field of Azure Cosmos DB document. - annotate a field in domain class with `@Id`, this field will be mapped to document `id` in Cosmos DB. - set name of this field to `id`, this field will be mapped to document `id` in Azure Cosmos DB. -- Custom collection Name. - By default, collection name will be class name of user domain class. To customize it, add the `@Document(collection="myCustomCollectionName")` annotation to the domain class. The collection field also supports SpEL expressions (eg. `collection = "${dynamic.collection.name}"` or `collection = "#{@someBean.getContainerName()}"`) in order to provide collection names programmatically/via configuration properties. +- Custom container Name. + By default, container name will be class name of user domain class. To customize it, add the `@Document(container="myCustomContainerName")` annotation to the domain class. The container field also supports SpEL expressions (eg. `container = "${dynamic.container.name}"` or `container = "#{@someBean.getContainerName()}"`) in order to provide container names programmatically/via configuration properties. - Custom IndexingPolicy By default, IndexingPolicy will be set by azure service. To customize it add annotation `@DocumentIndexingPolicy` to domain class. This annotation has 4 attributes to customize, see following: ```java // Indicate if indexing policy use automatic or not -boolean automatic() default Constants.DEFAULT_INDEXINGPOLICY_AUTOMATIC; +boolean automatic() default Constants.DEFAULT_INDEXING_POLICY_AUTOMATIC; // Indexing policy mode, option Consistent|Lazy|None. IndexingMode mode() default IndexingMode.CONSISTENT; @@ -53,11 +52,11 @@ String[] includePaths() default {}; String[] excludePaths() default {}; ``` -- Supports Optimistic Locking for specific collections, which means upserts/deletes by document will fail with an exception in case the document was modified by another process in the meanwhile. To enable Optimistic Locking for a collection, just create a string `_etag` field and mark it with the `@Version` annotation. See the following: +- Supports Optimistic Locking for specific containers, which means upserts/deletes by document will fail with an exception in case the document was modified by another process in the meanwhile. To enable Optimistic Locking for a container, just create a string `_etag` field and mark it with the `@Version` annotation. See the following: ```java -@Document(collection = "myCollection") +@Document(container = "myContainer") public class MyDocument { String id; String data; @@ -70,23 +69,27 @@ public class MyDocument { - Supports [Spring Data pagable and sort](https://docs.spring.io/spring-data/commons/docs/current/reference/html/#repositories.special-parameters). - Based on available RUs on the database account, cosmosDB can return documents less than or equal to the requested size. - Due to this variable number of returned documents in every iteration, user should not rely on the totalPageSize, and instead iterating over pageable should be done in this way. - + ```java -final CosmosPageRequest pageRequest = new CosmosPageRequest(0, pageSize, null); -Page page = repository.findAll(pageRequest); -List pageContent = page.getContent(); -while (page.hasNext()) { - Pageable nextPageable = page.nextPageable(); - page = repository.findAll(nextPageable); - pageContent = page.getContent(); +private List findAllWithPageSize(int pageSize) { + + final CosmosPageRequest pageRequest = new CosmosPageRequest(0, pageSize, null); + Page page = repository.findAll(pageRequest); + List pageContent = page.getContent(); + while (page.hasNext()) { + Pageable nextPageable = page.nextPageable(); + page = repository.findAll(nextPageable); + pageContent = page.getContent(); + } + return pageContent; } ``` - Supports [spring-boot-starter-data-rest](https://projects.spring.io/spring-data-rest/). - Supports List and nested type in domain class. -- Configurable ObjectMapper bean with unique name `cosmosdbObjectMapper`, only configure customized ObjectMapper if you really need to. e.g., +- Configurable ObjectMapper bean with unique name `cosmosObjectMapper`, only configure customized ObjectMapper if you really need to. e.g., ```java -@Bean(name = "cosmosdbObjectMapper") +@Bean(name = "cosmosObjectMapper") public ObjectMapper objectMapper() { return new ObjectMapper(); // Do configuration to the ObjectMapper if required } @@ -124,7 +127,7 @@ For reactive repository support, use `@EnableReactiveCosmosRepositories` 2.2.x supports Response Diagnostics String and Query Metrics. Set `queryMetricsEnabled` flag to true in application.properties to enable query metrics. In addition to setting the flag, implement `ResponseDiagnosticsProcessor` to log diagnostics information. - + ```java @Configuration @@ -148,19 +151,26 @@ public class AppConfiguration extends AbstractCosmosConfiguration { @Value("${azure.cosmos.queryMetricsEnabled}") private boolean queryMetricsEnabled; - private CosmosKeyCredential cosmosKeyCredential; + private AzureKeyCredential azureKeyCredential; public CosmosConfig getConfig() { - this.cosmosKeyCredential = new CosmosKeyCredential(key); - CosmosConfig cosmosConfig = CosmosConfig.builder(uri, - this.cosmosKeyCredential, dbName).build(); - cosmosConfig.setQueryMetricEnabled(queryMetricsEnabled); - cosmosConfig.setResponseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()); - return cosmosConfig; + this.azureKeyCredential = new AzureKeyCredential(key); + DirectConnectionConfig directConnectionConfig = new DirectConnectionConfig(); + GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); + CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() + .endpoint(uri) + .credential(azureKeyCredential) + .directMode(directConnectionConfig, gatewayConnectionConfig); + return CosmosConfig.builder() + .database(dbName) + .enableQueryMetrics(queryMetricsEnabled) + .cosmosClientBuilder(cosmosClientBuilder) + .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) + .build(); } public void switchToSecondaryKey() { - this.cosmosKeyCredential.key(secondaryKey); + this.azureKeyCredential.update(secondaryKey); } private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor { @@ -174,14 +184,20 @@ public class AppConfiguration extends AbstractCosmosConfiguration { } ``` Or if you want to customize your config: - + ```java public CosmosConfig getConfig() { - this.cosmosKeyCredential = new CosmosKeyCredential(key); - CosmosConfig cosmosConfig = CosmosConfig.builder(uri, this.cosmosKeyCredential, dbName).build(); - cosmosConfig.getConnectionPolicy().connectionMode(ConnectionMode.DIRECT); - cosmosConfig.getConnectionPolicy().maxPoolSize(1000); - return cosmosConfig; + DirectConnectionConfig directConnectionConfig = new DirectConnectionConfig(); + GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); + CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() + .endpoint(uri) + .directMode(directConnectionConfig, gatewayConnectionConfig); + return CosmosConfig.builder() + .database(dbName) + .enableQueryMetrics(queryMetricsEnabled) + .cosmosClientBuilder(cosmosClientBuilder) + .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) + .build(); } ``` By default, `@EnableCosmosRepositories` will scan the current package for any interfaces that extend one of Spring Data's repository interfaces. Using it to annotate your Configuration class to scan a different root package by `@EnableCosmosRepositories(basePackageClass=UserRepository.class)` if your project layout has multiple projects and it's not finding your repositories. @@ -192,12 +208,12 @@ Define a simple entity as Document in Azure Cosmos DB. You can define entities by adding the `@Document` annotation and specifying properties related to the container, such as the container name, request units (RUs), time to live, and auto-create container. -Containers are created automatically unless you don't want them to: Set `autoCreateCollection` to false in `@Document` annotation to disable auto creation of containers. +Containers will be created automatically unless you don't want them to: Set `autoCreateContainer` to false in `@Document` annotation to disable auto creation of containers. -Note: By default request units assigned to newly created containers is 4000. Specify different ru value to customize request units for container created by the SDK (minimum RU value is 400). +Note: By default request units assigned to newly created containers is 4000. Specify different ru value to customize request units for the container created by the SDK (minimum RU value is 400). ```java -@Document(collection = "myCollection", ru = "400") +@Document(container = "myContainer", ru = "400") public class User { private String id; private String firstName; @@ -249,11 +265,11 @@ public class User { ``` `id` field will be used as document id in Azure Cosmos DB. If you want use another field like `emailAddress` as document `id`, just annotate that field with `@Id` annotation. -Annotation `@Document(collection="mycollection")` is used to specify collection name in Azure Cosmos DB. +Annotation `@Document(container="myContainer")` is used to specify container name in Azure Cosmos DB. Annotation `@PartitionKey` on `lastName` field is used to specify this field be partition key in Azure Cosmos DB. ```java -@Document(collection = "mycollection") +@Document(container = "myContainer") public class UserSample { @Id private String emailAddress; @@ -263,7 +279,7 @@ public class UserSample { ### Create repositories Extends CosmosRepository interface, which provides Spring Data repository support. - + ```java @Repository diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java index d42d03f7d6cb..16d5c1857659 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/Constants.java @@ -24,7 +24,7 @@ public final class Constants { public static final String USER_AGENT_SUFFIX = "spring-data/"; - public static final String OBJECT_MAPPER_BEAN_NAME = "cosmosDbObjectMapper"; + public static final String OBJECT_MAPPER_BEAN_NAME = "cosmosObjectMapper"; public static final String ISO_8601_COMPATIBLE_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss:SSSXXX"; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java index 427066bdfdf4..979e44fa3358 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfiguration.java @@ -44,7 +44,12 @@ public class AppConfiguration extends AbstractCosmosConfiguration { public CosmosConfig getConfig() { this.azureKeyCredential = new AzureKeyCredential(key); - CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder().endpoint(uri).credential(azureKeyCredential); + DirectConnectionConfig directConnectionConfig = new DirectConnectionConfig(); + GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); + CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() + .endpoint(uri) + .credential(azureKeyCredential) + .directMode(directConnectionConfig, gatewayConnectionConfig); return CosmosConfig.builder() .database(dbName) .enableQueryMetrics(queryMetricsEnabled) diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java index 5780bcb251be..4e2f143e7629 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java @@ -11,13 +11,21 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; import com.azure.spring.data.cosmos.config.CosmosConfig; +import com.azure.spring.data.cosmos.core.ResponseDiagnostics; +import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; import com.azure.spring.data.cosmos.repository.config.EnableCosmosRepositories; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; +import org.springframework.lang.Nullable; @Configuration @EnableCosmosRepositories public class AppConfigurationCodeSnippet extends AbstractCosmosConfiguration { + + private static final Logger logger = LoggerFactory.getLogger(AppConfigurationCodeSnippet.class); + // configuration code @Value("${azure.cosmos.uri}") private String uri; @@ -35,11 +43,24 @@ public class AppConfigurationCodeSnippet extends AbstractCosmosConfiguration { private boolean queryMetricsEnabled; public CosmosConfig getConfig() { - AzureKeyCredential azureKeyCredential = new AzureKeyCredential(key); + DirectConnectionConfig directConnectionConfig = new DirectConnectionConfig(); + GatewayConnectionConfig gatewayConnectionConfig = new GatewayConnectionConfig(); + CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder() + .endpoint(uri) + .directMode(directConnectionConfig, gatewayConnectionConfig); return CosmosConfig.builder() .database(dbName) - .cosmosClientBuilder(new CosmosClientBuilder().credential(azureKeyCredential)) .enableQueryMetrics(queryMetricsEnabled) + .cosmosClientBuilder(cosmosClientBuilder) + .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) .build(); } + + private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor { + + @Override + public void processResponseDiagnostics(@Nullable ResponseDiagnostics responseDiagnostics) { + logger.info("Response Diagnostics {}", responseDiagnostics); + } + } } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/ObjectMapperConfigurationCodeSnippet.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/ObjectMapperConfigurationCodeSnippet.java index 87c9d23a4650..37737913b7b8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/ObjectMapperConfigurationCodeSnippet.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/ObjectMapperConfigurationCodeSnippet.java @@ -14,7 +14,7 @@ @Configuration public class ObjectMapperConfigurationCodeSnippet { - @Bean(name = "cosmosdbObjectMapper") + @Bean(name = "cosmosObjectMapper") public ObjectMapper objectMapper() { return new ObjectMapper(); // Do configuration to the ObjectMapper if required } diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/User.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/User.java index 76e22408a7cd..946dfcb6c761 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/User.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/User.java @@ -11,7 +11,7 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import com.azure.spring.data.cosmos.core.mapping.PartitionKey; -@Document(container = "myCollection", ru = "400") +@Document(container = "myContainer", ru = "400") public class User { private String id; private String firstName; diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserSample.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserSample.java index 97468f2314d6..3fcf775a27e8 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserSample.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserSample.java @@ -11,7 +11,7 @@ import com.azure.spring.data.cosmos.core.mapping.Document; import org.springframework.data.annotation.Id; -@Document(container = "mycollection") +@Document(container = "myContainer") public class UserSample { @Id private String emailAddress; From 2a95f0d80a618068d4c577aefed7eb34cdb8d3e1 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 16 Jul 2020 13:55:25 -0700 Subject: [PATCH 5/6] Removed unused imports --- .../java/com/azure/cosmos/AppConfigurationCodeSnippet.java | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java index 4e2f143e7629..985ea5c45175 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java +++ b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/AppConfigurationCodeSnippet.java @@ -8,7 +8,6 @@ * LINE NUMBERS OF EXISTING CODE SAMPLES. */ -import com.azure.core.credential.AzureKeyCredential; import com.azure.spring.data.cosmos.config.AbstractCosmosConfiguration; import com.azure.spring.data.cosmos.config.CosmosConfig; import com.azure.spring.data.cosmos.core.ResponseDiagnostics; From 80a72036f8b419278e80f25cc357093de60971ef Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 16 Jul 2020 14:37:01 -0700 Subject: [PATCH 6/6] Fixed code snippets because of unused removed import: --- sdk/cosmos/azure-spring-data-cosmos/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/cosmos/azure-spring-data-cosmos/README.md b/sdk/cosmos/azure-spring-data-cosmos/README.md index 285258598fb5..dea72254e765 100644 --- a/sdk/cosmos/azure-spring-data-cosmos/README.md +++ b/sdk/cosmos/azure-spring-data-cosmos/README.md @@ -184,7 +184,7 @@ public class AppConfiguration extends AbstractCosmosConfiguration { } ``` Or if you want to customize your config: - + ```java public CosmosConfig getConfig() { DirectConnectionConfig directConnectionConfig = new DirectConnectionConfig();