diff --git a/sdk/cosmos/azure-spring-data-cosmos/README.md b/sdk/cosmos/azure-spring-data-cosmos/README.md index 16f9b4d26b1be..dea72254e7658 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 } @@ -122,9 +125,9 @@ 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. - + ```java @Configuration @@ -133,34 +136,41 @@ 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.populateQueryMetrics}") - private boolean populateQueryMetrics; - - private CosmosKeyCredential cosmosKeyCredential; - - 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; + @Value("${azure.cosmos.queryMetricsEnabled}") + private boolean queryMetricsEnabled; + + private AzureKeyCredential azureKeyCredential; + + public CosmosConfig getConfig() { + 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 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; +public CosmosConfig getConfig() { + 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/pom.xml b/sdk/cosmos/azure-spring-data-cosmos/pom.xml index 96e0500a23b46..dc96240c398d4 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.3.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 @@ -198,13 +197,13 @@ 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] org.json:json:[20140107] 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] 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 47548ad5b229d..16d5c18576590 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 = "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/"; - public static final String OBJECTMAPPER_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/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 9c2d185320a29..0000000000000 --- 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/CosmosFactory.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosFactory.java new file mode 100644 index 0000000000000..3f59a7b04dd18 --- /dev/null +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/CosmosFactory.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.CosmosConfig; +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 CosmosFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(CosmosFactory.class); + + private final CosmosConfig 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 cosmosConfig cosmosConfig + */ + public CosmosFactory(@NonNull CosmosConfig cosmosConfig) { + validateConfig(cosmosConfig); + + this.config = cosmosConfig; + } + + /** + * 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(CosmosConfig cosmosConfig) { + final CosmosClientBuilder cosmosClientBuilder = cosmosConfig.getCosmosClientBuilder(); + cosmosClientBuilder.contentResponseOnWriteEnabled(true); + final String userAgentSuffixValue = getUserAgentSuffixValue(cosmosClientBuilder); + final String userAgentSuffix = getUserAgentSuffix() + userAgentSuffixValue; + + 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); + } catch (IllegalAccessException e) { + LOGGER.error("Error occurred while getting userAgentSuffix from CosmosClientBuilder", + e); + } + return ""; + } + + private void validateConfig(@NonNull CosmosConfig config) { + Assert.hasText(config.getDatabase(), "cosmos 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 Cosmos + * + * @return CosmosConfig + */ + public CosmosConfig getConfig() { + return config; + } +} diff --git a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosUtils.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosUtils.java new file mode 100644 index 0000000000000..9678f69d91c17 --- /dev/null +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/CosmosUtils.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 CosmosUtils { + + 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 + */ + 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/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 6e0e052d80256..0000000000000 --- 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/TelemetrySender.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/common/TelemetrySender.java index c57df311ff78f..96a34725b3793 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 cf9b204e4b2d6..0885555ac540c 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,101 @@ 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.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; +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, cosmos 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 CosmosFactory cosmosDBFactory(CosmosConfig config) { + return new CosmosFactory(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 cosmosFactory cosmosDbFactory + * @return CosmosClient bean */ @Bean - public CosmosDbFactory cosmosDbFactory(CosmosDBConfig config) { - return new CosmosDbFactory(config); + public CosmosAsyncClient cosmosAsyncClient(CosmosFactory cosmosFactory) { + return cosmosFactory.getCosmosAsyncClient(); } /** - * Declare CosmosTemplate bean. - * @param config of cosmosDbFactory - * @return CosmosTemplate bean - * @throws ClassNotFoundException if the class type is invalid + * Declare CosmosSyncClient bean. + * + * @param cosmosFactory 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(CosmosFactory cosmosFactory) { + return cosmosFactory.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 cosmosFactory 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(CosmosFactory cosmosFactory, + MappingCosmosConverter mappingCosmosConverter) { + return new CosmosTemplate(cosmosFactory, mappingCosmosConverter, + cosmosFactory.getConfig().getDatabase()); } /** - * Declare MappingCosmosConverter bean. - * @return MappingCosmosConverter bean - * @throws ClassNotFoundException if the class type is invalid + * Declare ReactiveCosmosTemplate bean. + * + * @param cosmosFactory cosmosDbFactory + * @param mappingCosmosConverter mappingCosmosConverter + * @return ReactiveCosmosTemplate bean */ @Bean - public MappingCosmosConverter mappingCosmosConverter() throws ClassNotFoundException { - return new MappingCosmosConverter(this.cosmosMappingContext(), objectMapper); + 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/CosmosConfig.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfig.java new file mode 100644 index 0000000000000..a89a83c0d02ed --- /dev/null +++ b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfig.java @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.spring.data.cosmos.config; + +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.spring.data.cosmos.core.ResponseDiagnosticsProcessor; + +import java.beans.ConstructorProperties; + +/** + * Config properties of CosmosDB + */ +public class CosmosConfig { + + private final CosmosClientBuilder cosmosClientBuilder; + + private final String database; + + private final boolean allowTelemetry; + + private final ResponseDiagnosticsProcessor responseDiagnosticsProcessor; + + private final boolean queryMetricsEnabled; + + /** + * 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 CosmosConfig(CosmosClientBuilder cosmosClientBuilder, String database, boolean allowTelemetry, + ResponseDiagnosticsProcessor responseDiagnosticsProcessor, boolean queryMetricsEnabled) { + this.cosmosClientBuilder = cosmosClientBuilder; + this.database = database; + this.allowTelemetry = allowTelemetry; + this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; + this.queryMetricsEnabled = queryMetricsEnabled; + } + + /** + * Gets the cosmos client builder used to build cosmos client + * + * @return cosmosClientBuilder + */ + public CosmosClientBuilder getCosmosClientBuilder() { + return cosmosClientBuilder; + } + + /** + * Checks if telemetry is allowed + * + * @return boolean + */ + public boolean isAllowTelemetry() { + return allowTelemetry; + } + + /** + * Gets response diagnostics processor + * + * @return ResponseDiagnosticsProcessor + */ + public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { + return responseDiagnosticsProcessor; + } + + /** + * Gets the option to enable query metrics + * + * @return boolean, whether to enable query metrics + */ + public boolean isQueryMetricsEnabled() { + return queryMetricsEnabled; + } + + /** + * Gets the database name + * + * @return database name + */ + public String getDatabase() { + return database; + } + + /** + * Create a CosmosConfigBuilder instance + * + * @return CosmosConfigBuilder + */ + public static CosmosConfigBuilder builder() { + return new CosmosConfigBuilder(); + } + + /** + * Builder class for cosmos config + */ + public static class CosmosConfigBuilder { + private String database; + private CosmosClientBuilder cosmosClientBuilder; + private boolean allowTelemetry; + private ResponseDiagnosticsProcessor responseDiagnosticsProcessor; + private boolean queryMetricsEnabled; + + CosmosConfigBuilder() { + } + + /** + * Set cosmosClientBuilder to use to build cosmos client + * + * @param cosmosClientBuilder cosmos client builder + * @return CosmosConfigBuilder + */ + public CosmosConfigBuilder cosmosClientBuilder(CosmosClientBuilder cosmosClientBuilder) { + this.cosmosClientBuilder = cosmosClientBuilder; + return this; + } + + /** + * Set allowTelemetry + * + * @param allowTelemetry value to initialize + * @return CosmosConfigBuilder + */ + public CosmosConfigBuilder allowTelemetry(boolean allowTelemetry) { + this.allowTelemetry = allowTelemetry; + return this; + } + + /** + * Set responseDiagnosticsProcessor + * + * @param responseDiagnosticsProcessor value to initialize + * @return CosmosConfigBuilder + */ + public CosmosConfigBuilder responseDiagnosticsProcessor(ResponseDiagnosticsProcessor + responseDiagnosticsProcessor) { + this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; + return this; + } + + /** + * Set queryMetricsEnabled + * + * @param queryMetricsEnabled value to initialize + * @return CosmosConfigBuilder + */ + public CosmosConfigBuilder enableQueryMetrics(boolean queryMetricsEnabled) { + this.queryMetricsEnabled = queryMetricsEnabled; + return this; + } + + /** + * Sets the database + * + * @param database database name + * @return CosmosConfigBuilder + */ + public CosmosConfigBuilder database(String database) { + this.database = database; + return this; + } + + /** + * Build a CosmosConfig instance + * + * @return CosmosConfig + */ + public CosmosConfig build() { + return new CosmosConfig(this.cosmosClientBuilder, this.database, this.allowTelemetry, + this.responseDiagnosticsProcessor, this.queryMetricsEnabled); + } + + @Override + public String toString() { + 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/config/CosmosConfigurationSupport.java b/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosConfigurationSupport.java index 07bd795e99fc2..46b240aff9c44 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 deleted file mode 100644 index 2cab7cb3466c0..0000000000000 --- a/sdk/cosmos/azure-spring-data-cosmos/src/main/java/com/azure/spring/data/cosmos/config/CosmosDBConfig.java +++ /dev/null @@ -1,397 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// 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.spring.data.cosmos.core.ResponseDiagnosticsProcessor; -import com.azure.spring.data.cosmos.exception.CosmosDBAccessException; -import org.springframework.util.Assert; - -import java.beans.ConstructorProperties; - -/** - * Config properties of CosmosDB - */ -public class CosmosDBConfig { - private String uri; - - private String key; - - private String database; - - private ConnectionPolicy connectionPolicy; - - private ConsistencyLevel consistencyLevel; - - private boolean allowTelemetry; - - private RequestOptions requestOptions; - - private CosmosKeyCredential cosmosKeyCredential; - - private ResponseDiagnosticsProcessor responseDiagnosticsProcessor; - - private boolean populateQueryMetrics; - - /** - * Initialization - * @param uri must not be {@literal null} - * @param key 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} - */ - @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; - 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; - } - - /** - * Gets consistency level - * @return ConsistencyLevel - */ - public ConsistencyLevel getConsistencyLevel() { - return consistencyLevel; - } - - /** - * Checks if telemetry is allowed - * @return boolean - */ - 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 - */ - public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { - return responseDiagnosticsProcessor; - } - - /** - * 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 - */ - 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()); - } - - /** - * 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 - */ - 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"); - } - } - - /** - * create a CosmosDBConfigBuilder instance - * @return CosmosDBConfigBuilder - */ - public static CosmosDBConfigBuilder defaultBuilder() { - return new CosmosDBConfigBuilder(); - } - - /** - * 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 boolean allowTelemetry; - private RequestOptions requestOptions; - private CosmosKeyCredential cosmosKeyCredential; - private ResponseDiagnosticsProcessor responseDiagnosticsProcessor; - private boolean populateQueryMetrics; - - 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 - * @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; - return this; - } - - /** - * Set allowTelemetry - * - * @param allowTelemetry value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder allowTelemetry(boolean allowTelemetry) { - this.allowTelemetry = allowTelemetry; - return this; - } - - /** - * Set requestOptions - * - * @param requestOptions value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder requestOptions(RequestOptions requestOptions) { - this.requestOptions = requestOptions; - return this; - } - - /** - * Set cosmosKeyCredential - * - * @param cosmosKeyCredential value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder cosmosKeyCredential(CosmosKeyCredential cosmosKeyCredential) { - this.cosmosKeyCredential = cosmosKeyCredential; - return this; - } - - /** - * Set responseDiagnosticsProcessor - * - * @param responseDiagnosticsProcessor value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder responseDiagnosticsProcessor(ResponseDiagnosticsProcessor - responseDiagnosticsProcessor) { - this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; - return this; - } - - /** - * Set populateQueryMetrics - * - * @param populateQueryMetrics value to initialize - * @return CosmosDBConfigBuilder - */ - public CosmosDBConfigBuilder populateQueryMetrics(boolean populateQueryMetrics) { - this.populateQueryMetrics = populateQueryMetrics; - return this; - } - - /** - * Build a CosmosDBConfig instance - * - * @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); - } - - /** - * Generate string info of instance - * - * @return String - */ - 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 - + ")"; - } - } -} 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 b723c4d9423e3..452d288f27486 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 c8ef03254879c..f24b8cb304c08 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.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,9 +26,9 @@ 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.azure.spring.data.cosmos.CosmosDbFactory; +import com.fasterxml.jackson.databind.JsonNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; @@ -57,39 +57,40 @@ 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 cosmosFactory must not be {@literal null} * @param mappingCosmosConverter 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.cosmosClient = cosmosDbFactory.getCosmosClient(); - this.responseDiagnosticsProcessor = cosmosDbFactory.getConfig().getResponseDiagnosticsProcessor(); - this.isPopulateQueryMetrics = cosmosDbFactory.getConfig().isPopulateQueryMetrics(); + this.cosmosAsyncClient = cosmosFactory.getCosmosAsyncClient(); + this.responseDiagnosticsProcessor = + cosmosFactory.getConfig().getResponseDiagnosticsProcessor(); + this.enableQueryMetrics = cosmosFactory.getConfig().isQueryMetricsEnabled(); } /** * Sets the application context + * * @param applicationContext must not be {@literal null} * @throws BeansException the bean exception */ @@ -97,8 +98,8 @@ 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 @@ -112,6 +113,7 @@ 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} @@ -122,33 +124,33 @@ public T insert(String containerName, T objectToSave, PartitionKey partition 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)) + 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; - return mappingCosmosConverter.read(domainType, response.properties()); + return toDomainObject(domainType, response.getItem()); } /** * Finds item by id + * * @param id must not be {@literal null} * @param domainType must not be {@literal null} * @param type class of domain type @@ -167,24 +169,23 @@ 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())); + 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(); } /** * 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} @@ -196,85 +197,86 @@ public T findById(String containerName, Object id, Class domainType) { 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); + CosmosUtils.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 -> - CosmosDBExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) + CosmosExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) .blockFirst(); } /** * Upserts an item with partition key + * * @param object upsert object - * @param partitionKey the partition key * @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 */ - 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 * @return upsert object entity */ - public T upsertAndReturnEntity(String containerName, T object, PartitionKey partitionKey) { + 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 -> CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + response.getDiagnostics(), null)) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to upsert item", throwable)) .block(); assert cosmosItemResponse != null; - return mappingCosmosConverter.read(domainType, cosmosItemResponse.properties()); + return toDomainObject(domainType, cosmosItemResponse.getItem()); } /** @@ -304,10 +306,10 @@ public List findAll(String containerName, final Class domainType) { 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 @@ -317,22 +319,23 @@ 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, + CosmosUtils.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)) + CosmosExceptionUtils.exceptionHandler("Failed to find items", throwable)) .collectList() .block(); } @@ -351,31 +354,19 @@ public void deleteAll(@NonNull String containerName, @NonNull Class domainTyp 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 -> { + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + response.getDiagnostics(), null); + }) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to delete container", throwable)) + .block(); } @Override @@ -385,75 +376,77 @@ 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)) + CosmosExceptionUtils.exceptionHandler("Failed to create database", throwable)) .flatMap(cosmosDatabaseResponse -> { - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosDatabaseResponse, null); - final CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties( - information.getContainerName(), "/" + CosmosUtils.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)) + CosmosExceptionUtils.exceptionHandler("Failed to create container", + throwable)) .doOnNext(cosmosContainerResponse -> - CosmosdbUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, - cosmosContainerResponse, null)); + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosContainerResponse.getDiagnostics(), null)); }) .block(); assert response != null; - return response.properties(); + return response.getProperties(); } /** - * 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 paritition key + * @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"); 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 -> + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + response.getDiagnostics(), null)) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to delete item", + throwable)) + .block(); } @Override @@ -463,45 +456,48 @@ 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), Part.IgnoreCaseType.NEVER)); + Collections.singletonList(ids), Part.IgnoreCaseType.NEVER)); return find(query, domainType, containerName); } /** * Finds the document query items + * * @param query The representation for query method. * @param domainType Class of domain * @param containerName Container name of database * @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 containerName Container name of database * @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. + * 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 @@ -511,24 +507,23 @@ public Boolean exists(@NonNull DocumentQuery query, @NonNull Class domain */ @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()); } @@ -537,56 +532,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)) + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + propertiesFeedResponse.getCosmosDiagnostics(), propertiesFeedResponse)) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to query items", throwable)) + CosmosExceptionUtils.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 @@ -600,7 +603,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); @@ -611,19 +614,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; } @@ -633,30 +633,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 -> + CosmosExceptionUtils.exceptionHandler("Failed to get count value", throwable)) + .doOnNext(response -> CosmosUtils.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 -> + CosmosExceptionUtils.exceptionHandler("Failed to execute query", + throwable)); } private List getPartitionKeyNames(Class domainType) { @@ -676,76 +677,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 -> { + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemFeedResponse.getCosmosDiagnostics(), cosmosItemFeedResponse); + return Flux.fromIterable(cosmosItemFeedResponse.getResults()); + }) + .onErrorResume(throwable -> + CosmosExceptionUtils.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 -> 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(); } - 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 04b4a447db3c9..fd47cffba2109 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 b2e0204aed119..b1e7eaf6dd2d9 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.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; @@ -23,9 +22,9 @@ 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.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,40 +44,37 @@ */ @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 cosmosFactory the cosmos db factory * @param mappingCosmosConverter the mappingCosmosConverter * @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.containerNameCache = new ArrayList<>(); - this.cosmosClient = cosmosDbFactory.getCosmosClient(); - this.responseDiagnosticsProcessor = cosmosDbFactory.getConfig().getResponseDiagnosticsProcessor(); - this.isPopulateQueryMetrics = cosmosDbFactory.getConfig().isPopulateQueryMetrics(); + this.cosmosAsyncClient = cosmosFactory.getCosmosAsyncClient(); + this.responseDiagnosticsProcessor = + cosmosFactory.getConfig().getResponseDiagnosticsProcessor(); + this.isPopulateQueryMetrics = cosmosFactory.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)) + CosmosExceptionUtils.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; - + CosmosUtils.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()); + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosContainerResponse.getDiagnostics(), null); return cosmosContainerResponse; }) .onErrorResume(throwable -> - CosmosDBExceptionUtils.exceptionHandler("Failed to create container", throwable)); + CosmosExceptionUtils.exceptionHandler("Failed to create container", + throwable)); }); } @@ -176,22 +168,23 @@ 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()); + 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)); } /** @@ -210,7 +203,7 @@ public Mono findById(Object id, Class domainType) { /** * Find by id * - * @param containerName the containername + * @param containerName the container name * @param id the id * @param domainType the entity class * @return Mono with the item or error @@ -221,26 +214,28 @@ public Mono findById(String containerName, Object id, Class domainType 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 -> { + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemFeedResponse.getCosmosDiagnostics(), + cosmosItemFeedResponse); + return Mono.justOrEmpty(cosmosItemFeedResponse + .getResults() + .stream() + .map(cosmosItem -> toDomainObject(domainType, cosmosItem)) + .findFirst()); + }) + .onErrorResume(throwable -> + CosmosExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)) + .next(); } /** @@ -257,18 +252,17 @@ 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 -> { + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return Mono.justOrEmpty(toDomainObject(domainType, + cosmosItemResponse.getItem())); + }) + .onErrorResume(throwable -> + CosmosExceptionUtils.findAPIExceptionHandler("Failed to find item", throwable)); } /** @@ -296,17 +290,19 @@ 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 JsonNode originalItem = + mappingCosmosConverter.writeJsonNode(objectToSave); + return cosmosAsyncClient.getDatabase(this.databaseName) + .getContainer(getContainerName(objectToSave.getClass())) + .createItem(originalItem, new CosmosItemRequestOptions()) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to insert item", throwable)) + .flatMap(cosmosItemResponse -> { + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return Mono.just(toDomainObject(domainType, + cosmosItemResponse.getItem())); + }); } /** @@ -318,38 +314,40 @@ public Mono insert(T objectToSave) { * @param partitionKey the partition key * @return Mono with the item or error */ - public Mono insert(String containerName, Object objectToSave, PartitionKey partitionKey) { + 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 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 -> + CosmosExceptionUtils.exceptionHandler("Failed to insert item", throwable)) + .flatMap(cosmosItemResponse -> { + CosmosUtils.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); } /** @@ -357,30 +355,28 @@ public Mono upsert(T object, PartitionKey partitionKey) { * * @param containerName the container name * @param object the object to save - * @param partitionKey the partition key * @return Mono with the item or error */ @Override - public Mono upsert(String containerName, T object, PartitionKey partitionKey) { + public Mono upsert(String containerName, T object) { final Class domainType = (Class) object.getClass(); - final CosmosItemProperties originalItem = mappingCosmosConverter.writeCosmosItemProperties(object); + 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 -> { + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return Mono.just(toDomainObject(domainType, + cosmosItemResponse.getItem())); + }) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to upsert item", throwable)); } /** @@ -397,63 +393,34 @@ public Mono deleteById(String containerName, Object id, PartitionKey parti 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 -> + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null)) + .onErrorResume(throwable -> + CosmosExceptionUtils.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) { + public Mono deleteAll(@NonNull String containerName, @NonNull Class domainType) { Assert.hasText(containerName, "container name should not be null, empty or only whitespaces"); - Assert.notNull(partitionKeyName, "partitionKeyName should not be null"); - 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(); } /** @@ -470,11 +437,10 @@ public Flux delete(DocumentQuery query, Class domainType, String conta Assert.notNull(domainType, "domainType should not be null."); 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)); } /** @@ -487,8 +453,8 @@ public Flux delete(DocumentQuery query, Class domainType, String conta */ @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)); } /** @@ -501,19 +467,20 @@ public Flux find(DocumentQuery query, Class domainType, String contain */ @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 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,7 +492,7 @@ 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); } /** @@ -537,7 +504,7 @@ public Mono count(String containerName) { */ @Override public Mono count(DocumentQuery query, String containerName) { - return count(query, true, containerName); + return getCountValue(query, containerName); } @Override @@ -545,42 +512,31 @@ 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 -> CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + null, feedResponse)) + .onErrorResume(throwable -> + CosmosExceptionUtils.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 -> + CosmosExceptionUtils.exceptionHandler("Failed to execute query", throwable)); } /** @@ -591,16 +547,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 -> + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosContainerResponse.getDiagnostics(), null)) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to delete container", + throwable)) + .block(); } /** @@ -613,25 +569,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 -> { + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + null, cosmosItemFeedResponse); + return Flux.fromIterable(cosmosItemFeedResponse.getResults()); + }) + .onErrorResume(throwable -> + CosmosExceptionUtils.exceptionHandler("Failed to query items", throwable)); } private void assertValidId(Object id) { @@ -651,48 +606,45 @@ 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 -> { + CosmosUtils.fillAndProcessResponseDiagnostics(responseDiagnosticsProcessor, + cosmosItemResponse.getDiagnostics(), null); + return cosmosItemResponse; + }) + .flatMap(objectCosmosItemResponse -> Mono.just(toDomainObject(domainType, jsonNode))) + .onErrorResume(throwable -> + CosmosExceptionUtils.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 c5c990c6b66d1..251eb6b402518 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) { @@ -133,13 +95,14 @@ public static class CosmosResponseStatistics { * @param feedResponse response from feed * @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 1eb96b4098090..577dc47e2a164 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 8fae263e43d53..260adf81ceb90 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.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.CosmosAccessException; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; 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.exception.CosmosDBAccessException; -import org.json.JSONObject; +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} */ 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 CosmosDBAccessException fail to map document value + * @throws CosmosAccessException fail to map document value */ - public CosmosItemProperties writeCosmosItemProperties(Object sourceEntity) { + public JsonNode writeJsonNode(Object sourceEntity) { if (sourceEntity == null) { return null; } @@ -121,26 +114,26 @@ 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); + throw new CosmosAccessException("Failed to map document value.", e); } 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 +152,7 @@ public ConversionService getConversionService() { /** * To get mapping context + * * @return MappingContext */ public MappingContext, CosmosPersistentProperty> getMappingContext() { @@ -171,7 +165,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 +181,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(); } else if (fromPropertyValue instanceof ZonedDateTime) { fromPropertyValue = ((ZonedDateTime) fromPropertyValue) - .format(DateTimeFormatter.ofPattern(ISO_8601_COMPATIBLE_DATE_PATTERN)); + .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 68719b5c3280c..e319398c49a0e 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; @@ -244,19 +244,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 c8f0d25d928fa..20f87b5fecf53 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 ff5e128bead15..fb0e53a752228 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 d460d2e266b37..22f92b367d105 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 189febbf8ce3f..570a12ed79ee5 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 511cea4d7fa35..3df927d705a3b 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 1e794e2d14e61..12f9386c16d0b 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 680b06ec2471e..937d70201aa52 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 5f42092af3c37..7ae26c79f335c 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 153a76b94909c..577be6de20c83 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/CosmosAccessException.java similarity index 62% 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 0a0d29725f39b..6f5b420d2cd74 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 @@ -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; @@ -12,22 +12,22 @@ * 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 CosmosClientException cosmosClientException; + protected final CosmosException cosmosException; /** * 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.cosmosClientException = null; + this.cosmosException = null; } /** @@ -36,12 +36,12 @@ 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 CosmosClientException) { - this.cosmosClientException = (CosmosClientException) cause; + if (cause instanceof CosmosException) { + this.cosmosException = (CosmosException) cause; } else { - this.cosmosClientException = null; + this.cosmosException = null; } } @@ -52,18 +52,18 @@ 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.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/CosmosExceptionUtils.java similarity index 62% 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 84c1dfae68ca4..98ce049271caf 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 @@ -2,16 +2,15 @@ // 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 { +public class CosmosExceptionUtils { /** * To throw a CosmosDBAccessException @@ -20,19 +19,19 @@ public class CosmosDBExceptionUtils { * @param throwable exception * @param type class of Mono * @return Mono instance - * @throws CosmosDBAccessException for operations on cosmosdb + * @throws CosmosAccessException 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); - throw new CosmosDBAccessException(message, unwrappedThrowable); + throw new CosmosAccessException(message, unwrappedThrowable); } /** - * 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 0e3968dc47706..6b42de838600d 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 0344ff842f502..9913389986431 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 59c95cb9c5af9..e1027f879cc36 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 2591d8502cda3..170604c72d5a2 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 4b35604e0f3a9..60a28bec9397d 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 20466b9231776..4ae480a3b25e4 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 5ac564c4aac25..a2a0cc4b62f87 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 c1c9d5aae91b0..ade7e47fbed2c 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 c195bc1339f94..c8541b2d9ff8e 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 db59937c57386..204c69d55b3ae 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 20c20a092323c..72ea2667d7f6d 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 ad4d06a2c7773..de43a7bbf5579 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 0611a21b5cc79..71e29ed825839 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 d7adefad76fca..91e2505dd2623 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 1ef6c82bd2dff..59ea8b6b0b92b 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 268a2c6914d8e..d7dfbb44ea8b3 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 924aa773ed490..3eab5d73fc0cf 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 6b13c5f98c009..f8433d9894179 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 20b191d066f24..de81d5415b913 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 ecf21da9d1109..0ea68ee18292f 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; @@ -52,7 +52,7 @@ public SimpleCosmosRepository(CosmosEntityInformation metadata, * Initialization * * @param metadata for cosmos entity information - * @param dbOperations for cosmosdb operation + * @param dbOperations for cosmosDB operation */ public SimpleCosmosRepository(CosmosEntityInformation metadata, CosmosOperations dbOperations) { @@ -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); @@ -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 27bfe96521072..4359c52c5e527 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 9fbdeefe25645..979e44fa33583 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.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.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 @@ -24,34 +25,41 @@ 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.populateQueryMetrics}") - private boolean populateQueryMetrics; + @Value("${azure.cosmos.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; + public CosmosConfig getConfig() { + 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 { 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 d44af1707fad7..985ea5c451751 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,40 +8,58 @@ * LINE NUMBERS OF EXISTING CODE SAMPLES. */ -import com.azure.data.cosmos.ConnectionMode; -import com.azure.data.cosmos.CosmosKeyCredential; 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; +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.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.populateQueryMetrics}") - private boolean populateQueryMetrics; + @Value("${azure.cosmos.queryMetricsEnabled}") + private boolean queryMetricsEnabled; + + public CosmosConfig getConfig() { + 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(); + } - private CosmosKeyCredential cosmosKeyCredential; + private static class ResponseDiagnosticsProcessorImplementation implements ResponseDiagnosticsProcessor { - 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; + @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/CosmosDbProperties.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/CosmosProperties.java similarity index 77% 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 345d13361811d..b073a18479a48 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; @@ -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 b68bf0f2b366e..0b28a7cad7fea 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 368b4f850b117..0251436588c22 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/ObjectMapperConfigurationCodeSnippet.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/ObjectMapperConfigurationCodeSnippet.java index 87c9d23a4650e..37737913b7b81 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 90a02d32c807f..946dfcb6c7610 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 = "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/UserRepositoryConfiguration.java b/sdk/cosmos/azure-spring-data-cosmos/src/samples/java/com/azure/cosmos/UserRepositoryConfiguration.java index f9d5c2a0baff6..727758ef6888f 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,9 +6,9 @@ * 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.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; @@ -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(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 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; + public CosmosConfig cosmosConfig() { + this.azureKeyCredential = new AzureKeyCredential(properties.getKey()); + return CosmosConfig.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 cdf690cd992ea..3fcf775a27e88 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 = "myContainer") 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 deleted file mode 100644 index b1f853dbe4031..0000000000000 --- 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/CosmosFactoryTestIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosFactoryTestIT.java new file mode 100644 index 0000000000000..0b33eb9bf9bf5 --- /dev/null +++ b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/CosmosFactoryTestIT.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.CosmosConfig; +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 CosmosFactoryTestIT { + + @Value("${cosmos.uri:}") + private String cosmosDbUri; + + @Value("${cosmos.key:}") + private String cosmosDbKey; + + @Test(expected = IllegalArgumentException.class) + public void testEmptyKey() { + final CosmosConfig cosmosConfig = CosmosConfig.builder() + .database(TestConstants.DB_NAME) + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(TestConstants.COSMOSDB_FAKE_HOST) + .key("")) + .build(); + new CosmosFactory(cosmosConfig).getCosmosSyncClient(); + } + + @Test + public void testInvalidEndpoint() { + final CosmosConfig cosmosConfig = CosmosConfig.builder() + .database(TestConstants.DB_NAME) + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(TestConstants.COSMOSDB_FAKE_HOST) + .key(TestConstants.COSMOSDB_FAKE_KEY)) + .build(); + final CosmosFactory factory = new CosmosFactory(cosmosConfig); + + assertThat(factory).isNotNull(); + } + + @Test + public void testConnectionPolicyUserAgentKept() throws IllegalAccessException { + final CosmosConfig cosmosConfig = CosmosConfig.builder() + .database(TestConstants.DB_NAME) + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(cosmosDbUri) + .key(cosmosDbKey)) + .build(); + + new CosmosFactory(cosmosConfig).getCosmosAsyncClient(); + + 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); + } +} 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 ba64a333b3039..0000000000000 --- 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 40eb9e50e07f6..f7e486aa23b97 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 6526575976625..40bf96bfa5136 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 e29aeed50175e..21000da50a2ba 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 af5f731364b2c..03d12c2048ee2 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 f05aef2174c10..3bcfbecfa6388 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 734a73707973b..77fc5dc997859 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.CosmosFactory; 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(); @@ -36,7 +38,7 @@ public class AbstractCosmosConfigurationIT { @Test public void containsExpressionResolver() { final AbstractApplicationContext context = new AnnotationConfigApplicationContext( - TestCosmosConfiguration.class); + TestCosmosConfiguration.class); assertNotNull(context.getBean(ExpressionResolver.class)); } @@ -44,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); } @@ -60,92 +62,95 @@ 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(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); + RequestOptionsConfiguration.class); + final CosmosFactory factory = context.getBean(CosmosFactory.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 - @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:}") private String database; @Mock - private CosmosClient mockClient; + 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(cosmosDbUri, cosmosDbKey, dbName).build(); + return CosmosConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(cosmosDbUri) + .key(cosmosDbKey)) + .database(dbName) + .build(); } @Override - public CosmosClient cosmosClient(CosmosDBConfig config) { + public CosmosAsyncClient cosmosAsyncClient(CosmosFactory cosmosFactory) { 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(); } } @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; - private RequestOptions getRequestOptions() { - final RequestOptions options = new RequestOptions(); - - options.setConsistencyLevel(ConsistencyLevel.CONSISTENT_PREFIX); - options.setScriptLoggingEnabled(true); - - return options; - } - @Bean - public CosmosDBConfig getConfig() { + public CosmosConfig 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 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 090902aca03aa..c8c3c5fff8837 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,12 +2,12 @@ // 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.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; @@ -39,7 +39,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; @@ -72,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); @@ -89,12 +102,12 @@ 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; } - insertedPerson = cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, null); + insertedPerson = cosmosTemplate.insert(Person.class.getSimpleName(), TEST_PERSON, new PartitionKey(TEST_PERSON.getLastName())); } @After @@ -107,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))); @@ -118,7 +131,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); } @@ -128,7 +141,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); @@ -147,7 +160,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); @@ -168,12 +181,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); @@ -185,8 +195,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); @@ -201,11 +210,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); @@ -218,11 +225,11 @@ public void testOptimisticLockWhenUpdatingWithWrongEtag() { updated.set_etag(WRONG_ETAG); try { - cosmosTemplate.upsert(Person.class.getSimpleName(), updated, null); - } catch (CosmosDBAccessException e) { - assertThat(e.getCosmosClientException()).isNotNull(); - final Throwable cosmosClientException = e.getCosmosClientException(); - assertThat(cosmosClientException).isInstanceOf(CosmosClientException.class); + cosmosTemplate.upsert(Person.class.getSimpleName(), updated); + } catch (CosmosAccessException e) { + 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(), @@ -242,13 +249,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); @@ -260,20 +266,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); } @@ -283,15 +288,14 @@ 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()), Part.IgnoreCaseType.NEVER); 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); // add ignoreCase testing @@ -299,10 +303,10 @@ public void testCountByQuery() { Collections.singletonList(TEST_PERSON_2.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); final DocumentQuery queryIgnoreCase = new DocumentQuery(criteriaIgnoreCase); - final long countIgnoreCase = cosmosTemplate.count(queryIgnoreCase, Person.class, containerName); + final long countIgnoreCase = cosmosTemplate.count(queryIgnoreCase, containerName); assertThat(countIgnoreCase).isEqualTo(1); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -312,8 +316,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); @@ -322,8 +325,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); @@ -332,8 +334,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); } @@ -343,8 +344,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", @@ -365,8 +365,7 @@ public void testPaginationQuery() { assertThat(pageIgnoreCase.getContent().size()).isEqualTo(1); PageTestUtils.validateLastPage(pageIgnoreCase, pageIgnoreCase.getContent().size()); - assertThat(responseDiagnosticsTestUtils.getCosmosResponseDiagnostics()).isNull(); - assertThat(responseDiagnosticsTestUtils.getFeedResponseDiagnostics()).isNotNull(); + assertThat(responseDiagnosticsTestUtils.getCosmosDiagnostics()).isNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics()).isNotNull(); assertThat(responseDiagnosticsTestUtils.getCosmosResponseStatistics().getRequestCharge()).isGreaterThan(0); } @@ -378,8 +377,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"); @@ -394,8 +392,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 dd63b2e930409..18db0b5311f63 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; @@ -21,7 +21,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; @@ -98,7 +97,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 adce25d05db49..487cdafaa0e86 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,10 +3,10 @@ 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.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; @@ -35,7 +35,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; @@ -56,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); @@ -69,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); @@ -154,8 +167,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); @@ -168,8 +180,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); } @@ -211,7 +222,7 @@ public void testCountForPartitionedCollectionByQuery() { Arrays.asList(TEST_PERSON_2.getFirstName()), Part.IgnoreCaseType.NEVER); 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); } @@ -222,8 +233,7 @@ public void testCountIgnoreCaseForPartitionedCollectionByQuery() { Arrays.asList(TEST_PERSON_2.getFirstName().toUpperCase()), Part.IgnoreCaseType.ALWAYS); final DocumentQuery queryIgnoreCase = new DocumentQuery(criteriaIgnoreCase); - final long countIgnoreCase = cosmosTemplate.count(queryIgnoreCase, - PartitionPerson.class, containerName); + final long countIgnoreCase = cosmosTemplate.count(queryIgnoreCase, containerName); assertThat(countIgnoreCase).isEqualTo(1); } @@ -233,7 +243,7 @@ public void testNonExistFieldValue() { Arrays.asList("non-exist-first-name"), Part.IgnoreCaseType.NEVER); 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 f183b45b3764e..8b85701646f8b 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,9 +3,10 @@ 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.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; @@ -15,9 +16,14 @@ 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 CosmosConfig cosmosConfig = CosmosConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint("") + .key("")) + .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 9971897c3afa0..c476de0f39d03 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,25 +2,28 @@ // 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.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 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,15 +38,13 @@ import reactor.test.StepVerifier; import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.Collections; 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 { @@ -66,13 +67,16 @@ 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("${cosmos.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; @@ -81,15 +85,16 @@ public class ReactiveCosmosTemplateIT { @Autowired private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; @Autowired private ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils; @Before public void setUp() throws ClassNotFoundException { if (!initialized) { - cosmosKeyCredential = new CosmosKeyCredential(dbConfig.getKey()); - final CosmosDbFactory dbFactory = new CosmosDbFactory(dbConfig); + azureKeyCredential = new AzureKeyCredential(cosmosDbKey); + cosmosConfig.getCosmosClientBuilder().credential(azureKeyCredential); + final CosmosFactory dbFactory = new CosmosFactory(cosmosConfig); final CosmosMappingContext mappingContext = new CosmosMappingContext(); personInfo = new CosmosEntityInformation<>(Person.class); @@ -99,8 +104,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, + cosmosConfig.getDatabase()); + cosmosTemplate.createContainerIfNotExists(personInfo).block(); initialized = true; } @@ -111,9 +117,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 @@ -125,14 +130,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(CosmosAccessException.class) + .verify(); } @Test @@ -143,14 +143,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); @@ -159,7 +159,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); } @@ -170,7 +170,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); } @@ -182,7 +182,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); } @@ -193,21 +193,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 @@ -216,9 +216,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 @@ -228,30 +228,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(); - } catch (CosmosDBAccessException cosmosDbAccessException) { - assertThat(cosmosDbAccessException.getCosmosClientException()).isNotNull(); - final Throwable cosmosClientException = cosmosDbAccessException.getCosmosClientException(); - assertThat(cosmosClientException).isInstanceOf(CosmosClientException.class); + cosmosTemplate.upsert(updated).block(); + } 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); - 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(); @@ -262,18 +263,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 @@ -282,13 +282,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 @@ -296,39 +295,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); @@ -344,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()); @@ -352,37 +351,35 @@ 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()); StepVerifier.create(personFluxIgnoreCase).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 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(); - 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 @@ -390,26 +387,27 @@ public void testCount() { final Mono count = cosmosTemplate.count(containerName); 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(); } @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(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 2e75a27f2e054..eda513baf86c3 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,10 +2,10 @@ // 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.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; @@ -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; @@ -52,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 = @@ -68,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; @@ -78,8 +82,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 @@ -139,8 +142,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(); } @@ -149,7 +151,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) @@ -177,7 +179,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/convert/ZonedDateTimeDeserializerTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/convert/ZonedDateTimeDeserializerTest.java index 64e3478866bac..88b593f2fe95d 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/core/converter/MappingCosmosConverterUnitTest.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/core/converter/MappingCosmosConverterUnitTest.java index b690633be817e..dc02b2a1ffb6e 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 ad7d2197baf44..f1e0ac86acb7b 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 3a4a64b55ed00..2fa20bf67bce4 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 77b75e914258c..e02dab6b3725c 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 2c1c9f6a63841..db7269e9830b9 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 1e04be72330f4..b80304e172e03 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 4bf8d7528f758..d1fa4472029eb 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 d426b7c241e7f..c847ff289555b 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 5d1a74296ad97..aab4c00198fbd 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 d3473617dcd75..82739641cc6a1 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 5c1a97acf7aba..581b546421e22 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 d80a8c02da403..3bb9359ec4454 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,8 +2,9 @@ // 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.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; @@ -22,7 +23,12 @@ public class PerfConfiguration extends AbstractCosmosConfiguration { private String cosmosDbKey; @Bean - public CosmosDBConfig getConfig() { - return CosmosDBConfig.builder(cosmosDbUri, cosmosDbKey, Constants.PERF_DATABASE_NAME).build(); + public CosmosConfig getConfig() { + return CosmosConfig.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 14256feed3451..009da215e7f10 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 eb6e15ba1a072..12d5b4d425bad 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 19cabb78bba7c..510ff1696e3e5 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 b9fa8bb4d6b86..5cd8706cc51cc 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) - .getContainer(containerName) - .queryItems(sql, feedOptions); + final Iterator> feedResponseIterator = + cosmosClient.getDatabase(dbName) + .getContainer(containerName) + .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,70 @@ 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 24061701bdb91..904e399372e24 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 14ced00fcd8f2..bc210f9e1f324 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 2488069f1d140..e8c055618b8bb 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 39291c39e1cd2..044efdfbbc892 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 80cb570fe9885..b59dce6509770 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 2556f379aa8e9..0fa81fed704ff 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.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.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.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; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -18,34 +17,21 @@ import org.springframework.util.StringUtils; @Configuration -@PropertySource(value = {"classpath:application.properties"}) +@PropertySource(value = { "classpath:application.properties" }) @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.connection-string:}") - private String connectionString; - - @Value("${cosmosdb.database:}") + @Value("${cosmos.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("${cosmos.queryMetricsEnabled}") + private boolean queryMetricsEnabled; @Bean public ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils() { @@ -53,21 +39,17 @@ public ResponseDiagnosticsTestUtils responseDiagnosticsTestUtils() { } @Bean - public CosmosDBConfig getConfig() { + public CosmosConfig 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(); + 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 440cc1d93be99..73945c6eeee2d 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 30b78a63900ef..57e518e03ef69 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/AddressRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/AddressRepositoryIT.java index 0a78bfebcbe8d..024d38ad5e919 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 bbcb0aedadfce..7c256d9a8e03a 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 7c5253e0c1187..40fb7e95f3b10 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.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.cosmos.models.CosmosContainerProperties; +import com.azure.cosmos.models.IndexingPolicy; +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.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; -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; @@ -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); @@ -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 5b2eb1866a5e3..a910b94adb38e 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 ec95314fb903e..f19eaa83834eb 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.CosmosAccessException; 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; @@ -131,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()); @@ -144,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 11e0a8a504dd4..eda4c1579c593 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.CosmosAccessException; 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; @@ -240,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 dee802834c9a6..5361cee83e5d5 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.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.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.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; 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; @@ -65,7 +64,7 @@ public class PageableAddressRepositoryIT { private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; @Before public void setUp() { @@ -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 = - cosmosClient.getDatabase(dbConfig.getDatabase()) + final CosmosAsyncClient cosmosClient = applicationContext.getBean(CosmosAsyncClient.class); + final Flux> feedResponseFlux = + cosmosClient.getDatabase(cosmosConfig.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 a941af82390b2..4998508bee5b7 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.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.cosmos.CosmosAsyncClient; +import com.azure.cosmos.models.CosmosQueryRequestOptions; +import com.azure.cosmos.models.FeedResponse; +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.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; @@ -52,7 +57,7 @@ public class PageableMemoRepositoryIT { private ApplicationContext applicationContext; @Autowired - private CosmosDBConfig dbConfig; + private CosmosConfig cosmosConfig; private static Set memoSet; @@ -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); - return cosmosClient.getDatabase(dbConfig.getDatabase()) - .getContainer(entityInformation.getContainerName()) - .queryItems(query, options); + final CosmosAsyncClient cosmosClient = applicationContext.getBean(CosmosAsyncClient.class); + return cosmosClient.getDatabase(cosmosConfig.getDatabase()) + .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 20cc38a9ce36e..a7f06d1a5b194 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 3910aa2a3be1f..eeececf58d128 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 0402c2c9e8c77..d75df0779a2f8 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.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; 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; @@ -141,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"); @@ -156,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/QuestionRepositoryIT.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/QuestionRepositoryIT.java index 5410ca9f445ef..5cd17d70a034c 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 d23671b4aa311..afa98e5f4b69b 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.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; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -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 85% 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 608e26b6b60b0..bf2300cc0f2be 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 @@ -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.spring.data.cosmos.config.CosmosDBConfig; +import com.azure.cosmos.CosmosClientBuilder; +import com.azure.spring.data.cosmos.CosmosFactory; +import com.azure.spring.data.cosmos.common.TestConstants; +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; 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; @@ -31,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 @@ -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 CosmosConfig cosmosConfig = CosmosConfig.builder() + .cosmosClientBuilder(new CosmosClientBuilder() + .endpoint(dbUri) + .key(dbKey)) + .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/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 f7a0bbbc9a5c3..131fe0c756268 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 36948a82e2876..c836ebb73f8f5 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 69cb5ee06e9e2..8b7fed4669321 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 e13047d28442f..1b3da03888f0f 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 6a15bd90b4fae..ed015518d9bd5 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 295d7f3d7c66a..eb064a5f94782 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 56f51bef2f60c..1c7bbbe057aaf 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 df1a33f88ae17..1fefb26bbc729 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 11c63be3e4afa..e305178f6b753 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 c930ca9d8486e..562dab56f24a0 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 0d043875c1288..f45d4621ec9ed 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/SortedProjectRepository.java b/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/repository/SortedProjectRepository.java index e841aaab8d2c4..0bdd871e184b6 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 0026cc7b8ad13..a46748b0c523a 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 e543d74b07be5..698aa5d25780e 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 3a5ecd362fe30..55c18653afe34 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; @@ -58,7 +58,7 @@ public void testCustomContainerName() { new CosmosEntityInformation(VersionedVolunteer.class); final String containerName = entityInformation.getContainerName(); - assertThat(containerName).isEqualTo("testCollection"); + assertThat(containerName).isEqualTo("testContainer"); } @Test @@ -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 cb205d625cc98..d7c2c127ef504 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 12b7c8f46f80b..5f47ae7f03be3 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,9 +1,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} +cosmos.uri=${ACCOUNT_HOST} +cosmos.key=${ACCOUNT_KEY} +cosmos.secondaryKey=${SECONDARY_ACCOUNT_KEY} dynamic.collection.name=spel-property-collection # Performance test configurations @@ -12,4 +9,4 @@ perf.batch.size=3 perf.acceptance.percentage=10 # Populate query metrics -cosmosdb.populateQueryMetrics=true +cosmos.queryMetricsEnabled=true