diff --git a/sdk/cosmos/azure-cosmos-benchmark/src/main/java/com/azure/cosmos/benchmark/SyncBenchmark.java b/sdk/cosmos/azure-cosmos-benchmark/src/main/java/com/azure/cosmos/benchmark/SyncBenchmark.java index ccf392f48ba7..59e68c589de6 100644 --- a/sdk/cosmos/azure-cosmos-benchmark/src/main/java/com/azure/cosmos/benchmark/SyncBenchmark.java +++ b/sdk/cosmos/azure-cosmos-benchmark/src/main/java/com/azure/cosmos/benchmark/SyncBenchmark.java @@ -354,6 +354,6 @@ V getOrThrow(Future f) { } PojoizedJson toPojoizedJson(CosmosItemResponse resp) throws Exception { - return resp.getResource(); + return resp.getItem(); } } diff --git a/sdk/cosmos/azure-cosmos/pom.xml b/sdk/cosmos/azure-cosmos/pom.xml index 3dc004fbd739..67dc96018856 100644 --- a/sdk/cosmos/azure-cosmos/pom.xml +++ b/sdk/cosmos/azure-cosmos/pom.xml @@ -280,18 +280,6 @@ Licensed under the MIT License. - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 1.8 - 1.8 - false - - - org.apache.maven.plugins maven-surefire-plugin diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncContainer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncContainer.java index c0ab49055954..acf136eccab4 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncContainer.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncContainer.java @@ -214,6 +214,7 @@ public Mono> createItem(T item, CosmosItemRequest if (options == null) { options = new CosmosItemRequestOptions(); } + @SuppressWarnings("unchecked") Class itemType = (Class) item.getClass(); RequestOptions requestOptions = ModelBridgeInternal.toRequestOptions(options); return database.getDocClientWrapper() @@ -256,6 +257,7 @@ public Mono> upsertItem(T item, CosmosItemRequest if (options == null) { options = new CosmosItemRequestOptions(); } + @SuppressWarnings("unchecked") Class itemType = (Class) item.getClass(); return this.getDatabase().getDocClientWrapper() .upsertDocument(this.getLink(), item, @@ -312,7 +314,7 @@ public CosmosPagedFlux readAllItems(FeedOptions options, Class classTy * @param the type parameter * @param query the query. * @param classType the class type - * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an + * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an * error. */ public CosmosPagedFlux queryItems(String query, Class classType) { @@ -330,7 +332,7 @@ public CosmosPagedFlux queryItems(String query, Class classType) { * @param query the query. * @param options the feed options. * @param classType the class type - * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an + * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an * error. */ public CosmosPagedFlux queryItems(String query, FeedOptions options, Class classType) { @@ -347,7 +349,7 @@ public CosmosPagedFlux queryItems(String query, FeedOptions options, Clas * @param the type parameter * @param querySpec the SQL query specification. * @param classType the class type - * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an + * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an * error. */ public CosmosPagedFlux queryItems(SqlQuerySpec querySpec, Class classType) { @@ -365,7 +367,7 @@ public CosmosPagedFlux queryItems(SqlQuerySpec querySpec, Class classT * @param querySpec the SQL query specification. * @param options the feed options. * @param classType the class type - * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an + * @return a {@link CosmosPagedFlux} containing one or several feed response pages of the obtained items or an * error. */ public CosmosPagedFlux queryItems(SqlQuerySpec querySpec, FeedOptions options, Class classType) { @@ -475,6 +477,7 @@ public Mono> replaceItem( options = new CosmosItemRequestOptions(); } ModelBridgeInternal.setPartitionKey(options, partitionKey); + @SuppressWarnings("unchecked") Class itemType = (Class) item.getClass(); return this.getDatabase() .getDocClientWrapper() @@ -494,7 +497,7 @@ public Mono> replaceItem( * @param partitionKey the partition key * @return an {@link Mono} containing the cosmos item resource response. */ - public Mono deleteItem(String itemId, PartitionKey partitionKey) { + public Mono> deleteItem(String itemId, PartitionKey partitionKey) { return deleteItem(itemId, partitionKey, new CosmosItemRequestOptions()); } @@ -510,7 +513,7 @@ public Mono deleteItem(String itemId, PartitionKey part * @param options the request options * @return an {@link Mono} containing the cosmos item resource response. */ - public Mono deleteItem( + public Mono> deleteItem( String itemId, PartitionKey partitionKey, CosmosItemRequestOptions options) { if (options == null) { @@ -521,7 +524,7 @@ public Mono deleteItem( return this.getDatabase() .getDocClientWrapper() .deleteDocument(getItemLink(itemId), requestOptions) - .map(response -> ModelBridgeInternal.createCosmosAsyncItemResponseWithObjectType(response, Object.class)) + .map(response -> ModelBridgeInternal.createCosmosAsyncItemResponseWithObjectType(response)) .single(); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosContainer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosContainer.java index 3149c89c5a7d..38ced2367e69 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosContainer.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosContainer.java @@ -203,6 +203,8 @@ public CosmosItemResponse upsertItem(T item) throws CosmosClientException * @return the cosmos sync item response * @throws CosmosClientException the cosmos client exception */ + @SuppressWarnings("unchecked") + // Note: @kushagraThapar and @moderakh to ensure this casting is valid public CosmosItemResponse upsertItem(Object item, CosmosItemRequestOptions options) throws CosmosClientException { return (CosmosItemResponse) this.mapItemResponseAndBlock(this.asyncContainer.upsertItem(item, options)); @@ -218,9 +220,9 @@ public CosmosItemResponse upsertItem(Object item, CosmosItemRequestOption CosmosItemResponse mapItemResponseAndBlock(Mono> itemMono) throws CosmosClientException { try { - return (CosmosItemResponse) itemMono - .map(this::convertResponse) - .block(); + return itemMono + .map(this::convertResponse) + .block(); } catch (Exception ex) { final Throwable throwable = Exceptions.unwrap(ex); if (throwable instanceof CosmosClientException) { @@ -231,8 +233,8 @@ CosmosItemResponse mapItemResponseAndBlock(Mono deleteItemMono) throws - CosmosClientException { + private CosmosItemResponse mapDeleteItemResponseAndBlock(Mono> deleteItemMono) + throws CosmosClientException { try { return deleteItemMono .map(this::convertResponse) @@ -347,7 +349,7 @@ public CosmosItemResponse replaceItem(T item, * @return the cosmos sync item response * @throws CosmosClientException the cosmos client exception */ - public CosmosItemResponse deleteItem(String itemId, PartitionKey partitionKey, + public CosmosItemResponse deleteItem(String itemId, PartitionKey partitionKey, CosmosItemRequestOptions options) throws CosmosClientException { return this.mapDeleteItemResponseAndBlock(asyncContainer.deleteItem(itemId, partitionKey, options)); } @@ -372,8 +374,8 @@ public CosmosScripts getScripts() { * @param response the cosmos item response * @return the cosmos sync item response */ - private CosmosItemResponse convertResponse(CosmosAsyncItemResponse response) { - return ModelBridgeInternal.createCosmosItemResponse(response); + private CosmosItemResponse convertResponse(CosmosAsyncItemResponse response) { + return ModelBridgeInternal.createCosmosItemResponse(response); } private CosmosPagedIterable getCosmosPagedIterable(CosmosPagedFlux cosmosPagedFlux) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosItemProperties.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosItemProperties.java index b54d38b08dba..a9894501dd18 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosItemProperties.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/CosmosItemProperties.java @@ -108,8 +108,8 @@ static List getTypedResultsFromV2Results(List results, Class * @return the object * @throws IOException the io exception */ - public T getObject(Class klass) throws IOException { - return (T) MAPPER.readValue(this.toJson(), klass); + public T getObject(Class klass) throws IOException { + return MAPPER.readValue(this.toJson(), klass); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/NotFoundException.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/NotFoundException.java index 4738ca39834c..e7ae65242a2f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/NotFoundException.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/NotFoundException.java @@ -11,6 +11,7 @@ import com.azure.cosmos.models.CosmosError; import java.net.URI; +import java.util.HashMap; import java.util.Map; /** @@ -79,7 +80,7 @@ public NotFoundException(String message, HttpHeaders headers, URI requestUri) { } NotFoundException(Exception innerException) { - this(RMResources.NotFound, innerException, (Map) null, null); + this(RMResources.NotFound, innerException, (Map) null, null); } NotFoundException(String message, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ResourceId.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ResourceId.java index b84159170803..b36e064dee00 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ResourceId.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/ResourceId.java @@ -180,21 +180,21 @@ public static Pair tryParse(String id) { ResourceId.blockCopy(buffer, 8, subCollRes, 0, 8); long subCollectionResource = ByteBuffer.wrap(buffer, 8, 8).getLong(); - if ((subCollRes[7] >> 4) == (byte) CollectionChildResourceType.Document) { + if ((subCollRes[7] >> 4) == CollectionChildResourceType.Document) { rid.document = subCollectionResource; if (buffer.length == 20) { rid.attachment = ByteBuffer.wrap(buffer, 16, 4).getInt(); } - } else if (Math.abs(subCollRes[7] >> 4) == (byte) CollectionChildResourceType.StoredProcedure) { + } else if (Math.abs(subCollRes[7] >> 4) == CollectionChildResourceType.StoredProcedure) { rid.storedProcedure = subCollectionResource; - } else if ((subCollRes[7] >> 4) == (byte) CollectionChildResourceType.Trigger) { + } else if ((subCollRes[7] >> 4) == CollectionChildResourceType.Trigger) { rid.trigger = subCollectionResource; - } else if ((subCollRes[7] >> 4) == (byte) CollectionChildResourceType.UserDefinedFunction) { + } else if ((subCollRes[7] >> 4) == CollectionChildResourceType.UserDefinedFunction) { rid.userDefinedFunction = subCollectionResource; - } else if ((subCollRes[7] >> 4) == (byte) CollectionChildResourceType.Conflict) { + } else if ((subCollRes[7] >> 4) == CollectionChildResourceType.Conflict) { rid.conflict = subCollectionResource; - } else if ((subCollRes[7] >> 4) == (byte) CollectionChildResourceType.PartitionKeyRange) { + } else if ((subCollRes[7] >> 4) == CollectionChildResourceType.PartitionKeyRange) { rid.partitionKeyRange = subCollectionResource; } else { return Pair.of(false, rid); @@ -372,7 +372,7 @@ public ResourceId getDocumentId() { rid.document = this.document; return rid; } - + public long getPartitionKeyRange() { return this.partitionKeyRange; } @@ -456,22 +456,22 @@ else if (this.database != 0) if (this.documentCollection != 0) ResourceId.blockCopy( - convertToBytesUsingByteBuffer(this.documentCollection), + convertToBytesUsingByteBuffer(this.documentCollection), 0, val, 4, 4); else if (this.user != 0) - ResourceId.blockCopy(convertToBytesUsingByteBuffer(this.user), + ResourceId.blockCopy(convertToBytesUsingByteBuffer(this.user), 0, val, 4, 4); if (this.storedProcedure != 0) ResourceId.blockCopy( - convertToBytesUsingByteBuffer(this.storedProcedure), + convertToBytesUsingByteBuffer(this.storedProcedure), 0, val, 8, 8); else if (this.trigger != 0) ResourceId.blockCopy(convertToBytesUsingByteBuffer(this.trigger), 0, val, 8, 8); else if (this.userDefinedFunction != 0) ResourceId.blockCopy( - convertToBytesUsingByteBuffer(this.userDefinedFunction), + convertToBytesUsingByteBuffer(this.userDefinedFunction), 0, val, 8, 8); else if (this.conflict != 0) ResourceId.blockCopy(convertToBytesUsingByteBuffer(this.conflict), @@ -481,16 +481,16 @@ else if (this.document != 0) 0, val, 8, 8); else if (this.permission != 0) ResourceId.blockCopy( - convertToBytesUsingByteBuffer(this.permission), + convertToBytesUsingByteBuffer(this.permission), 0, val, 8, 8); else if (this.partitionKeyRange != 0) ResourceId.blockCopy( - convertToBytesUsingByteBuffer(this.partitionKeyRange), + convertToBytesUsingByteBuffer(this.partitionKeyRange), 0, val, 8, 8); if (this.attachment != 0) ResourceId.blockCopy( - convertToBytesUsingByteBuffer(this.attachment), + convertToBytesUsingByteBuffer(this.attachment), 0, val, 16, 4); return val; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java index 6724c2f98af1..9e6b5d890c7a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentClientImpl.java @@ -547,7 +547,7 @@ private Flux> createQuery( IDocumentQueryClient queryClient = DocumentQueryClientImpl(RxDocumentClientImpl.this); Flux> executionContext = DocumentQueryExecutionContextFactory.createDocumentQueryExecutionContextAsync(queryClient, resourceTypeEnum, klass, sqlQuery , options, queryResourceLink, false, activityId); - return executionContext.flatMap(IDocumentQueryExecutionContext::executeAsync); + return executionContext.flatMap(IDocumentQueryExecutionContext::executeAsync); } @@ -1569,7 +1569,7 @@ private Flux> createReadManyQuery( activityId, klass, resourceTypeEnum); - return executionContext.flatMap(IDocumentQueryExecutionContext::executeAsync); + return executionContext.flatMap(IDocumentQueryExecutionContext::executeAsync); } @Override diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentServiceResponse.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentServiceResponse.java index d0a3637d742a..ca7099c9a112 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentServiceResponse.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/RxDocumentServiceResponse.java @@ -114,6 +114,8 @@ public T getResource(Class c) { return resource; } + @SuppressWarnings("unchecked") + // Given cls (where cls == Class), objectNode is first decoded to cls and then casted to T. public List getQueryResponse(Class c) { byte[] responseBody = this.getResponseBodyAsByteArray(); if (responseBody == null) { diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SessionContainer.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SessionContainer.java index 2483b8f62665..7d81175538c4 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SessionContainer.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/SessionContainer.java @@ -263,7 +263,7 @@ private void addSessionToken(ResourceId resourceId, String partitionKeyRangeId, if (existingTokens == null) { logger.info("Registering a new collection resourceId [{}] in SessionTokens", resourceId); ConcurrentHashMap tokens = - new ConcurrentHashMap(200, 0.75f, 2000); + new ConcurrentHashMap(200, 0.75f, 2000); tokens.put(partitionKeyRangeId, parsedSessionToken); return tokens; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/VectorSessionToken.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/VectorSessionToken.java index 861e0e8ccf75..1a4f1d655117 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/VectorSessionToken.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/VectorSessionToken.java @@ -13,6 +13,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import static com.azure.cosmos.implementation.Utils.ValueHolder; @@ -109,6 +110,15 @@ public boolean equals(Object obj) { return this.version == other.version && this.globalLsn == other.globalLsn && this.areRegionProgressEqual(other.localLsnByRegion); + + } + + @Override + public int hashCode() { +// TODO: @kushagraThapar, @moderakh, mbhaskar to identify proper implementation. +// Issue: https://github.com/Azure/azure-sdk-for-java/issues/9046 +// return Objects.hash(this.version, this.globalLsn, this.localLsnByRegion); + return super.hashCode(); } public boolean isValid(ISessionToken otherSessionToken) throws CosmosClientException { @@ -198,7 +208,7 @@ public ISessionToken merge(ISessionToken obj) throws CosmosClientException { return new VectorSessionToken( Math.max(this.version, other.version), Math.max(this.globalLsn, other.globalLsn), - (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(highestLocalLsnByRegion)); + (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(highestLocalLsnByRegion)); } public String convertToString() { @@ -275,7 +285,7 @@ private static boolean tryParseSessionToken( lsnByRegion.put(regionId.v, localLsn.v); } - localLsnByRegion.v = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(lsnByRegion); + localLsnByRegion.v = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(lsnByRegion); return true; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/ChangeFeedContextClient.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/ChangeFeedContextClient.java index d06743defdd6..6c55ccc013b3 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/ChangeFeedContextClient.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/ChangeFeedContextClient.java @@ -84,7 +84,7 @@ Mono> createItem(CosmosAsyncContainer containerLi * @param options the request options. * @return an {@link Mono} containing the cosmos item resource response with the deleted item or an error. */ - Mono deleteItem(String itemId, PartitionKey partitionKey, + Mono> deleteItem(String itemId, PartitionKey partitionKey, CosmosItemRequestOptions options); /** diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedContextClientImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedContextClientImpl.java index 3276dd52c691..216378824017 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedContextClientImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedContextClientImpl.java @@ -123,7 +123,7 @@ public Mono> createItem(CosmosAsyncContainer cont } @Override - public Mono deleteItem(String itemId, PartitionKey partitionKey, + public Mono> deleteItem(String itemId, PartitionKey partitionKey, CosmosItemRequestOptions options) { return cosmosContainer.deleteItem(itemId, partitionKey, options) .publishOn(this.rxScheduler); @@ -137,7 +137,7 @@ public Mono> replaceItem(String itemId, Partition } @Override - public Mono> readItem(String itemId, PartitionKey partitionKey, + public Mono> readItem(String itemId, PartitionKey partitionKey, CosmosItemRequestOptions options, Class itemType) { return cosmosContainer.readItem(itemId, partitionKey, options, itemType) .publishOn(this.rxScheduler); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedObserverFactoryImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedObserverFactoryImpl.java index cbf3f5f7c870..0fa9355a2a13 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedObserverFactoryImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/ChangeFeedObserverFactoryImpl.java @@ -10,16 +10,16 @@ * DEFAULT implementation for {@link ChangeFeedObserverFactory}. */ public class ChangeFeedObserverFactoryImpl implements ChangeFeedObserverFactory { - private final Class observerType; + private final Class observerType; - public ChangeFeedObserverFactoryImpl(Class observerType) { + public ChangeFeedObserverFactoryImpl(Class observerType) { this.observerType = observerType; } @Override public ChangeFeedObserver createObserver() { try { - return (ChangeFeedObserver) observerType.newInstance(); + return observerType.newInstance(); } catch (IllegalAccessException | InstantiationException ex) { throw new ObserverException(ex); } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/DefaultObserver.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/DefaultObserver.java index ef5d7fa02008..573718a19748 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/DefaultObserver.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/DefaultObserver.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.changefeed.implementation; -import com.azure.cosmos.implementation.CosmosItemProperties; import com.azure.cosmos.implementation.changefeed.ChangeFeedObserver; import com.azure.cosmos.implementation.changefeed.ChangeFeedObserverCloseReason; import com.azure.cosmos.implementation.changefeed.ChangeFeedObserverContext; @@ -14,7 +13,7 @@ import java.util.List; import java.util.function.Consumer; -class DefaultObserver implements ChangeFeedObserver { +class DefaultObserver implements ChangeFeedObserver { private static final Logger log = LoggerFactory.getLogger(DefaultObserver.class); private final Consumer> consumer; @@ -36,7 +35,7 @@ public void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReas public Mono processChanges(ChangeFeedObserverContext context, List docs) { log.info("Start processing from thread {}", Thread.currentThread().getId()); try { - //TODO for later: convert to user T here unless T is JsonNode when we want to add additional support to + //TODO for later: convert to user T here unless T is JsonNode when we want to add additional support to // user types. consumer.accept(docs); log.info("Done processing from thread {}", Thread.currentThread().getId()); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/PartitionProcessorImpl.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/PartitionProcessorImpl.java index 989d5d83aeab..1880dcfb3ddb 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/PartitionProcessorImpl.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/changefeed/implementation/PartitionProcessorImpl.java @@ -132,12 +132,15 @@ public Mono run(CancellationToken cancellationToken) { case PARTITION_NOT_FOUND: { this.resultException = new PartitionNotFoundException("Partition not found.", this.lastContinuation); } + break; case PARTITION_SPLIT: { this.resultException = new PartitionSplitException("Partition split.", this.lastContinuation); } + break; case UNDEFINED: { this.resultException = new RuntimeException(clientException); } + break; case MAX_ITEM_COUNT_TOO_LARGE: { if (this.options.getMaxItemCount() == null) { this.options.setMaxItemCount(DefaultMaxItemCount); @@ -163,6 +166,7 @@ public Mono run(CancellationToken cancellationToken) { }).flatMap(values -> Flux.empty()); } } + break; default: { logger.error("Unrecognized Cosmos exception returned error code {}", docDbError, clientException); this.resultException = new RuntimeException(clientException); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/BarrierRequestHelper.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/BarrierRequestHelper.java index aedd4694759d..8c36903ac4ad 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/BarrierRequestHelper.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/BarrierRequestHelper.java @@ -49,10 +49,10 @@ public static Mono createAsync( if (!isCollectionHeadRequest) { // DB Feed barrierLsnRequest = RxDocumentServiceRequest.create( - OperationType.HeadFeed, - (String) null, - (ResourceType) ResourceType.Database, - (Map) null); + OperationType.HeadFeed, + null, + ResourceType.Database, + null); } else if (request.getIsNameBased()) { // Name based server request diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/ConsistencyWriter.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/ConsistencyWriter.java index 0b54ca731c6b..a1f952e0c16f 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/ConsistencyWriter.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/ConsistencyWriter.java @@ -310,7 +310,7 @@ private Mono waitForWriteBarrierAsync(RxDocumentServiceRequest barrierR //get max global committed lsn from current batch of responses, then update if greater than max of all batches. long maxGlobalCommittedLsn = (responses != null) ? - (Long) responses.stream().map(s -> s.globalCommittedLSN).max(ComparatorUtils.NATURAL_COMPARATOR).orElse(0L) : + responses.stream().map(s -> s.globalCommittedLSN).max(ComparatorUtils.naturalComparator()).orElse(0L) : 0L; maxGlobalCommittedLsnReceived.set(maxGlobalCommittedLsnReceived.get() > maxGlobalCommittedLsn ? maxGlobalCommittedLsnReceived.get() : maxGlobalCommittedLsn); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolver.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolver.java index aa5898a7772a..d101893a81b0 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolver.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolver.java @@ -88,10 +88,11 @@ Mono openAsync(DocumentCollection collection) { List ranges = collectionRoutingMap.v.getOrderedPartitionKeyRanges().stream().map(range -> new PartitionKeyRangeIdentity(collection.getResourceId(), range.getId())).collect(Collectors.toList()); List> tasks = new ArrayList<>(); - Mono[] array = new Mono[this.addressCacheByEndpoint.values().size()]; for (EndpointCache endpointCache : this.addressCacheByEndpoint.values()) { tasks.add(endpointCache.addressCache.openAsync(collection, ranges)); } + @SuppressWarnings({"rawtypes", "unchecked"}) + Mono[] array = new Mono[this.addressCacheByEndpoint.values().size()]; return Flux.mergeDelayError(Queues.SMALL_BUFFER_SIZE, tasks.toArray(array)).then(); }); } @@ -125,7 +126,7 @@ private EndpointCache getOrAddEndpoint(URI endpoint) { }); if (this.addressCacheByEndpoint.size() > this.maxEndpoints) { - List allEndpoints = new ArrayList(this.endpointManager.getWriteEndpoints()); + List allEndpoints = new ArrayList<>(this.endpointManager.getWriteEndpoints()); allEndpoints.addAll(this.endpointManager.getReadEndpoints()); Collections.reverse(allEndpoints); LinkedList endpoints = new LinkedList<>(allEndpoints); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/QuorumReader.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/QuorumReader.java index f67fd895ef5a..bcfcd3cadca4 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/QuorumReader.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/QuorumReader.java @@ -320,9 +320,9 @@ private Mono readLsn = new ValueHolder(-1); - ValueHolder globalCommittedLSN = new ValueHolder(-1); - ValueHolder storeResult = new ValueHolder(null); + ValueHolder readLsn = new ValueHolder<>(-1L); + ValueHolder globalCommittedLSN = new ValueHolder<>(-1L); + ValueHolder storeResult = new ValueHolder<>(null); if (this.isQuorumMet( responseResult, diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/SharedTransportClient.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/SharedTransportClient.java index 2389b038c9ee..31dff5e48551 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/SharedTransportClient.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/SharedTransportClient.java @@ -18,6 +18,12 @@ * This class uses a shared RntbdTransportClient for multiple Cosmos Clients. * The benefit is the underlying connections can be shared if possible across multiple Cosmos client instances. */ +// We suppress the "try" warning here because the close() method's signature +// allows it to throw InterruptedException which is strongly advised against +// by AutoCloseable (see: http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html#close()). +// close() will never throw an InterruptedException but the exception remains in the +// signature for backwards compatibility purposes. +@SuppressWarnings("try") public class SharedTransportClient extends TransportClient { private static final Logger logger = LoggerFactory.getLogger(SharedTransportClient.class); private static final AtomicInteger counter = new AtomicInteger(0); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreClientFactory.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreClientFactory.java index 103b7f9cb737..346f87da29c9 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreClientFactory.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreClientFactory.java @@ -14,6 +14,12 @@ // Links: // https://msdata.visualstudio.com/CosmosDB/SDK/_workitems/edit/262496 +// We suppress the "try" warning here because the close() method's signature +// allows it to throw InterruptedException which is strongly advised against +// by AutoCloseable (see: http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html#close()). +// close() will never throw an InterruptedException but the exception remains in the +// signature for backwards compatibility purposes. +@SuppressWarnings("try") public class StoreClientFactory implements AutoCloseable { private final Configs configs; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreReader.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreReader.java index 746ce230188f..7e189f5fabf3 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreReader.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/StoreReader.java @@ -385,8 +385,10 @@ private Mono readMultipleReplicasInternalAsync(RxDocumentServ // TODO: enforceSessionCheck is true, replace with true boolean enforceSessionCheck = true; - MutableVolatile hasGoneException = new MutableVolatile(false); - MutableVolatile shortCircuitResult = new MutableVolatile(); + MutableVolatile hasGoneException + = new MutableVolatile<>(false); + MutableVolatile shortCircuitResult + = new MutableVolatile<>(); return Flux.defer(() -> readFromReplicas( diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/TransportClient.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/TransportClient.java index edbc6146854e..38be7c02a27a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/TransportClient.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/TransportClient.java @@ -8,6 +8,12 @@ import java.net.URI; +// We suppress the "try" warning here because the close() method's signature +// allows it to throw InterruptedException which is strongly advised against +// by AutoCloseable (see: http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html#close()). +// close() will never throw an InterruptedException but the exception remains in the +// signature for backwards compatibility purposes. +@SuppressWarnings("try") public abstract class TransportClient implements AutoCloseable { // Uses requests's ResourceOperation to determine the operation diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdContextRequestEncoder.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdContextRequestEncoder.java index bfca1fdbdd2c..a14df0c4ada1 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdContextRequestEncoder.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdContextRequestEncoder.java @@ -9,7 +9,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -final class RntbdContextRequestEncoder extends MessageToByteEncoder { +final class RntbdContextRequestEncoder extends MessageToByteEncoder { private static final Logger Logger = LoggerFactory.getLogger(RntbdContextRequestEncoder.class); @@ -23,7 +23,7 @@ final class RntbdContextRequestEncoder extends MessageToByteEncoder { */ @Override public boolean acceptOutboundMessage(final Object message) { - return message instanceof RntbdContextRequest; + return message.getClass() == RntbdContextRequest.class; } /** @@ -37,18 +37,17 @@ public boolean acceptOutboundMessage(final Object message) { * @throws IllegalStateException is thrown if an error occurs */ @Override - protected void encode(final ChannelHandlerContext context, final Object message, final ByteBuf out) throws IllegalStateException { + protected void encode(final ChannelHandlerContext context, final RntbdContextRequest message, final ByteBuf out) throws IllegalStateException { - final RntbdContextRequest request = (RntbdContextRequest)message; out.markWriterIndex(); try { - request.encode(out); + message.encode(out); } catch (final IllegalStateException error) { out.resetWriterIndex(); throw error; } - Logger.debug("{}: ENCODE COMPLETE: request={}", context.channel(), request); + Logger.debug("{}: ENCODE COMPLETE: request={}", context.channel(), message); } } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestRecord.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestRecord.java index 447ca6340022..308cf95dcee7 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestRecord.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdRequestRecord.java @@ -35,10 +35,10 @@ public final class RntbdRequestRecord extends CompletableFuture { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); - private static final AtomicIntegerFieldUpdater REQUEST_LENGTH = + private static final AtomicIntegerFieldUpdater REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); - private static final AtomicIntegerFieldUpdater RESPONSE_LENGTH = + private static final AtomicIntegerFieldUpdater RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater STAGE = diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponse.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponse.java index fc517e7b73fc..a998ea4aab62 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponse.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/directconnectivity/rntbd/RntbdResponse.java @@ -34,7 +34,7 @@ public final class RntbdResponse implements ReferenceCounted { // region Fields - private static final AtomicIntegerFieldUpdater REFERENCE_COUNT = + private static final AtomicIntegerFieldUpdater REFERENCE_COUNT = AtomicIntegerFieldUpdater.newUpdater(RntbdResponse.class, "referenceCount"); @JsonSerialize(using = PayloadSerializer.class) diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OrderByUtils.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OrderByUtils.java index 3ea30e6da23d..35f99a630b1a 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OrderByUtils.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/query/OrderByUtils.java @@ -29,6 +29,7 @@ public static Flux> orderedMerge(Class< List> documentProducers, Map queryMetricsMap, Map targetRangeToOrderByContinuationTokenMap) { + @SuppressWarnings("unchecked") Flux>[] fluxes = documentProducers .subList(0, documentProducers.size()) .stream() diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/LocationCache.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/LocationCache.java index 3695fd756ad0..1d538d20e881 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/LocationCache.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/LocationCache.java @@ -175,7 +175,7 @@ public URI resolveServiceEndpoint(RxDocumentServiceRequest request) { } } - public boolean shouldRefreshEndpoints(Utils.ValueHolder canRefreshInBackground) { + public boolean shouldRefreshEndpoints(Utils.ValueHolder canRefreshInBackground) { canRefreshInBackground.v = true; DatabaseAccountLocationsInfo currentLocationInfo = this.locationInfo; String mostPreferredLocation = Utils.firstOrDefault(currentLocationInfo.preferredLocations); @@ -454,7 +454,7 @@ private UnmodifiableList getPreferredAvailableEndpoints(UnmodifiableMap(endpoints); } private UnmodifiableMap getEndpointByLocation(Iterable locations, @@ -477,8 +477,9 @@ private UnmodifiableMap getEndpointByLocation(Iterable(parsedLocations); + + return (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(endpointsByLocation); } private boolean canUseMultipleWriteLocations() { @@ -564,8 +565,10 @@ class DatabaseAccountLocationsInfo { public DatabaseAccountLocationsInfo(List preferredLocations, URI defaultEndpoint) { this.preferredLocations = new UnmodifiableList<>(preferredLocations.stream().map(loc -> loc.toLowerCase()).collect(Collectors.toList())); - this.availableWriteEndpointByLocation = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); - this.availableReadEndpointByLocation = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); + this.availableWriteEndpointByLocation + = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); + this.availableReadEndpointByLocation + = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>()); this.availableReadLocations = new UnmodifiableList<>(Collections.emptyList()); this.availableWriteLocations = new UnmodifiableList<>(Collections.emptyList()); this.readEndpoints = new UnmodifiableList<>(Collections.singletonList(defaultEndpoint)); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/MurmurHash3_32.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/MurmurHash3_32.java index 7287934ea34b..77da5d03e371 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/MurmurHash3_32.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/MurmurHash3_32.java @@ -24,6 +24,7 @@ public class MurmurHash3_32 { * @param seed an integer to be used as hash seed * @return the hash value */ + @SuppressWarnings("fallthrough") // Fall through is expected public static int hash(byte[] data, int len, int seed) { final int c1 = 0xcc9e2d51; final int c2 = 0x1b873593; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternal.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternal.java index a19d4db2d7e6..c56eb07dcb46 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternal.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/routing/PartitionKeyInternal.java @@ -170,6 +170,21 @@ public boolean equals(Object obj) { return this.compareTo(pki) == 0; } + @Override + public int hashCode() { +// TODO: @kushagraThapar, @moderakh, mbhaskar to identify proper implementation. +// Issue: https://github.com/Azure/azure-sdk-for-java/issues/9046 +// if (this.components == null || this.components.size() == 0) { +// return 0; +// } +// int [] ordinals = new int[this.components.size()]; +// for (int i = 0; i < this.components.size(); i++) { +// ordinals[i] = this.components.get(i).GetTypeOrdinal(); +// } +// return Arrays.hashCode(ordinals); + return super.hashCode(); + } + public int compareTo(PartitionKeyInternal other) { if (other == null) { throw new IllegalArgumentException("other"); diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosAsyncItemResponse.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosAsyncItemResponse.java index a21a85fa482a..19a9458e4369 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosAsyncItemResponse.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosAsyncItemResponse.java @@ -34,6 +34,7 @@ public class CosmosAsyncItemResponse { * * @return the resource */ + @SuppressWarnings("unchecked") // Casting getProperties() to T is safe given T is of CosmosItemProperties. public T getItem() { if (item != null) { return item; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosItemResponse.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosItemResponse.java index a8e2bb74a1af..47d2e2d7a8c5 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosItemResponse.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosItemResponse.java @@ -15,9 +15,9 @@ * @param the type parameter */ public class CosmosItemResponse { - private final CosmosAsyncItemResponse responseWrapper; + private final CosmosAsyncItemResponse responseWrapper; - CosmosItemResponse(CosmosAsyncItemResponse response) { + CosmosItemResponse(CosmosAsyncItemResponse response) { this.responseWrapper = response; } @@ -26,9 +26,8 @@ public class CosmosItemResponse { * * @return the resource */ - @SuppressWarnings("unchecked") - public T getResource() { - return (T) responseWrapper.getItem(); + public T getItem() { + return responseWrapper.getItem(); } /** diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosResponse.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosResponse.java index 86eb23092a62..abfa0f94b6b6 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosResponse.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/CosmosResponse.java @@ -15,9 +15,9 @@ */ public class CosmosResponse { private T properties; - protected final ResourceResponse resourceResponseWrapper; + protected final ResourceResponse resourceResponseWrapper; - protected CosmosResponse(ResourceResponse resourceResponse) { + protected CosmosResponse(ResourceResponse resourceResponse) { this.resourceResponseWrapper = resourceResponse; } @@ -26,7 +26,7 @@ protected CosmosResponse(T properties) { this.resourceResponseWrapper = null; } - protected CosmosResponse(ResourceResponse resourceResponse, T properties) { + protected CosmosResponse(ResourceResponse resourceResponse, T properties) { this.resourceResponseWrapper = resourceResponse; this.properties = properties; } diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/JsonSerializable.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/JsonSerializable.java index 3bac9be8605c..f177d7d0bea4 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/JsonSerializable.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/JsonSerializable.java @@ -140,6 +140,7 @@ protected void populatePropertyBag() { * * @return the HashMap. */ + @SuppressWarnings("unchecked") public Map getMap() { return getMapper().convertValue(this.propertyBag, HashMap.class); } @@ -321,6 +322,8 @@ public Double getDouble(String propertyName) { * @return the object value. * @throws IllegalStateException thrown if an error occurs */ + @SuppressWarnings("unchecked") + // Implicit or explicit cast to T is done only after checking values are assignable from Class. public T getObject(String propertyName, Class c, boolean... convertFromCamelCase) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { JsonNode jsonObj = propertyBag.get(propertyName); @@ -367,6 +370,8 @@ public T getObject(String propertyName, Class c, boolean... convertFromCa * @return the object collection. * @throws IllegalStateException thrown if an error occurs */ + @SuppressWarnings("unchecked") + // Implicit or explicit cast to T is done only after checking values are assignable from Class. public List getList(String propertyName, Class c, boolean... convertFromCamelCase) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { ArrayNode jsonArray = (ArrayNode) this.propertyBag.get(propertyName); @@ -567,6 +572,8 @@ private String toPrettyJson(Object object) { * @throws IllegalArgumentException thrown if an error occurs * @throws IllegalStateException thrown when objectmapper is unable to read tree */ + @SuppressWarnings("unchecked") + // Implicit or explicit cast to T is done after checking values are assignable from Class. public T toObject(Class c) { // TODO: We have to remove this if we do not want to support CosmosItemProperties anymore, and change all the // tests accordingly diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java index 56758a9549a5..9b77308ea307 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/models/ModelBridgeInternal.java @@ -72,8 +72,8 @@ public static CosmosAsyncItemResponse createCosmosAsyncItemResponse(Resou return new CosmosAsyncItemResponse<>(response, classType); } - public static CosmosAsyncItemResponse createCosmosAsyncItemResponseWithObjectType(ResourceResponse response, Class classType) { - return new CosmosAsyncItemResponse(response, classType); + public static CosmosAsyncItemResponse createCosmosAsyncItemResponseWithObjectType(ResourceResponse response) { + return new CosmosAsyncItemResponse<>(response, Object.class); } public static CosmosAsyncPermissionResponse createCosmosAsyncPermissionResponse(ResourceResponse response, @@ -405,7 +405,7 @@ public static void populatePropertyBagJsonSerializable(JsonSerializable jsonSeri jsonSerializable.populatePropertyBag(); } - public static JsonSerializable instantiateJsonSerializable(ObjectNode objectNode, Class klassType) { + public static JsonSerializable instantiateJsonSerializable(ObjectNode objectNode, Class klassType) { try { // the hot path should come through here to avoid serialization/deserialization if (klassType.equals(Document.class) || klassType.equals(OrderByRowResult.class) || klassType.equals(CosmosItemProperties.class) diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosClientExceptionTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosClientExceptionTest.java index a48293a7e703..69b1906ced2d 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosClientExceptionTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosClientExceptionTest.java @@ -76,21 +76,21 @@ public void headerNotNull3() { @Test(groups = { "unit" }) public void headerNotNull4() { - CosmosClientException dce = BridgeInternal.createCosmosClientException(0, (CosmosError) null, (Map) null); + CosmosClientException dce = BridgeInternal.createCosmosClientException(0, (CosmosError) null, (Map) null); assertThat(dce.getResponseHeaders()).isNotNull(); assertThat(dce.getResponseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull5() { - CosmosClientException dce = BridgeInternal.createCosmosClientException((String) null, 0, (CosmosError) null, (Map) null); + CosmosClientException dce = BridgeInternal.createCosmosClientException((String) null, 0, (CosmosError) null, (Map) null); assertThat(dce.getResponseHeaders()).isNotNull(); assertThat(dce.getResponseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull6() { - CosmosClientException dce = BridgeInternal.createCosmosClientException((String) null, (Exception) null, (Map) null, 0, (String) null); + CosmosClientException dce = BridgeInternal.createCosmosClientException((String) null, (Exception) null, (Map) null, 0, (String) null); assertThat(dce.getResponseHeaders()).isNotNull(); assertThat(dce.getResponseHeaders()).isEmpty(); } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosItemTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosItemTest.java index 95b6d605608c..a34dc182271e 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosItemTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosItemTest.java @@ -120,7 +120,7 @@ public void deleteItem() throws Exception { CosmosItemResponse itemResponse = container.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - CosmosItemResponse deleteResponse = container.deleteItem(properties.getId(), + CosmosItemResponse deleteResponse = container.deleteItem(properties.getId(), new PartitionKey(properties.get("mypk")), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosKeyCredentialTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosKeyCredentialTest.java index 1a222956ed40..2bb84b39ea6d 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosKeyCredentialTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosKeyCredentialTest.java @@ -248,7 +248,7 @@ public void deleteDocumentWithSecondaryKey(String documentId) throws Interrupted CosmosItemRequestOptions options = new CosmosItemRequestOptions(); ModelBridgeInternal.setPartitionKey(options, new PartitionKey(docDefinition.get("mypk"))); - Mono deleteObservable = container.deleteItem(docDefinition.getId(), + Mono> deleteObservable = container.deleteItem(docDefinition.getId(), new PartitionKey(docDefinition.get( "mypk")), options); @@ -373,6 +373,7 @@ public void afterClass() { safeClose(client); } + @SuppressWarnings({"unchecked", "rawtypes"}) public void validateSuccess(Mono single, CosmosResponseValidator validator) { validateSuccess(single, validator, TIMEOUT); } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosResponseDiagnosticsTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosResponseDiagnosticsTest.java index 20e9cc585ba9..a63aa6a0e8fb 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosResponseDiagnosticsTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosResponseDiagnosticsTest.java @@ -190,7 +190,10 @@ private CosmosItemProperties getCosmosItemProperties() { private List getStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { Field storeResponseStatisticsField = ClientSideRequestStatistics.class.getDeclaredField("supplementalResponseStatisticsList"); storeResponseStatisticsField.setAccessible(true); - return (List) storeResponseStatisticsField.get(requestStatistics); + @SuppressWarnings({"unchecked"}) + List list + = (List) storeResponseStatisticsField.get(requestStatistics); + return list; } private void clearStoreResponseStatistics(ClientSideRequestStatistics requestStatistics) throws Exception { diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosResponseValidator.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosResponseValidator.java index 58ddfcb4c60a..9de10f959a5e 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosResponseValidator.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosResponseValidator.java @@ -29,6 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; +@SuppressWarnings("rawtypes") public interface CosmosResponseValidator { void validate(T cosmosResponse); @@ -91,7 +92,7 @@ public void validate(T resourceResponse) { public Builder indexingMode(IndexingMode mode) { validators.add(new CosmosResponseValidator() { - + @Override public void validate(CosmosAsyncContainerResponse resourceResponse) { assertThat(resourceResponse.getProperties()).isNotNull(); @@ -134,29 +135,29 @@ public void validate(CosmosAsyncContainerResponse resourceResponse) { Iterator> compositeIndexesReadIterator = resourceResponse.getProperties() .getIndexingPolicy().getCompositeIndexes().iterator(); Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); - + ArrayList readIndexesStrings = new ArrayList(); ArrayList writtenIndexesStrings = new ArrayList(); - + while (compositeIndexesReadIterator.hasNext() && compositeIndexesWrittenIterator.hasNext()) { Iterator compositeIndexReadIterator = compositeIndexesReadIterator.next().iterator(); Iterator compositeIndexWrittenIterator = compositeIndexesWrittenIterator.next().iterator(); StringBuilder readIndexesString = new StringBuilder(); StringBuilder writtenIndexesString = new StringBuilder(); - + while (compositeIndexReadIterator.hasNext() && compositeIndexWrittenIterator.hasNext()) { CompositePath compositePathRead = compositeIndexReadIterator.next(); CompositePath compositePathWritten = compositeIndexWrittenIterator.next(); - + readIndexesString.append(compositePathRead.getPath() + ":" + compositePathRead.getOrder() + ";"); writtenIndexesString.append(compositePathWritten.getPath() + ":" + compositePathRead.getOrder() + ";"); } - + readIndexesStrings.add(readIndexesString.toString()); writtenIndexesStrings.add(writtenIndexesString.toString()); } - + assertThat(readIndexesStrings).containsExactlyInAnyOrderElementsOf(writtenIndexesStrings); } @@ -185,7 +186,7 @@ public void validate(CosmosAsyncContainerResponse resourceResponse) { ArrayList readSpatialTypes = new ArrayList(); ArrayList writtenSpatialTypes = new ArrayList(); - + Iterator spatialTypesReadIterator = spatialSpecRead.getSpatialTypes().iterator(); Iterator spatialTypesWrittenIterator = spatialSpecWritten.getSpatialTypes().iterator(); @@ -193,11 +194,11 @@ public void validate(CosmosAsyncContainerResponse resourceResponse) { readSpatialTypes.add(spatialTypesReadIterator.next()); writtenSpatialTypes.add(spatialTypesWrittenIterator.next()); } - + readIndexMap.put(readPath, readSpatialTypes); writtenIndexMap.put(writtenPath, writtenSpatialTypes); } - + for (Entry> entry : readIndexMap.entrySet()) { Assertions.assertThat(entry.getValue()) .containsExactlyInAnyOrderElementsOf(writtenIndexMap.get(entry.getKey())); @@ -217,7 +218,7 @@ public void validate(CosmosAsyncStoredProcedureResponse resourceResponse) { }); return this; } - + public Builder notNullEtag() { validators.add(new CosmosResponseValidator() { diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/MultipleCosmosClientsWithTransportClientSharingTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/MultipleCosmosClientsWithTransportClientSharingTest.java index 82aad0a9beef..04fd0fd04583 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/MultipleCosmosClientsWithTransportClientSharingTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/MultipleCosmosClientsWithTransportClientSharingTest.java @@ -142,7 +142,7 @@ public void deleteItem() { CosmosItemResponse itemResponse = container1.createItem(properties); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - CosmosItemResponse deleteResponse = container1.deleteItem(properties.getId(), + CosmosItemResponse deleteResponse = container1.deleteItem(properties.getId(), new PartitionKey(properties.get("mypk")), options); assertThat(deleteResponse.getStatusCode()).isEqualTo(204); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/RetryContextOnDiagnosticTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/RetryContextOnDiagnosticTest.java index 559cbd4e5919..d2503b5ea3cf 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/RetryContextOnDiagnosticTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/RetryContextOnDiagnosticTest.java @@ -48,6 +48,7 @@ public class RetryContextOnDiagnosticTest extends TestSuiteBase { @Test(groups = {"simple"}) public void backoffRetryUtilityExecuteRetry() throws Exception { + @SuppressWarnings("unchecked") Callable> callbackMethod = Mockito.mock(Callable.class); serviceRequest = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); retryPolicy = new TestRetryPolicy(); @@ -64,6 +65,7 @@ public void backoffRetryUtilityExecuteRetry() throws Exception { @Test(groups = {"simple"}) public void backoffRetryUtilityExecuteRetryWithFailure() throws Exception { + @SuppressWarnings("unchecked") Callable> callbackMethod = Mockito.mock(Callable.class); serviceRequest = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); retryPolicy = new TestRetryPolicy(); @@ -81,6 +83,7 @@ public void backoffRetryUtilityExecuteRetryWithFailure() throws Exception { } @Test(groups = {"simple"}) + @SuppressWarnings("unchecked") public void backoffRetryUtilityExecuteAsync() { Function, Mono> inBackoffAlternateCallbackMethod = Mockito.mock(Function.class); Function, Mono> parameterizedCallbackMethod = Mockito.mock(Function.class); @@ -100,6 +103,7 @@ public void backoffRetryUtilityExecuteAsync() { } @Test(groups = {"simple"}) + @SuppressWarnings("unchecked") public void backoffRetryUtilityExecuteAsyncWithFailure() { Function, Mono> inBackoffAlternateCallbackMethod = Mockito.mock(Function.class); Function, Mono> parameterizedCallbackMethod = Mockito.mock(Function.class); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ConsistencyTests2.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ConsistencyTests2.java index 9fa06a6b7e2b..ca39e63be90c 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ConsistencyTests2.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ConsistencyTests2.java @@ -180,7 +180,7 @@ public void validateNoChargeOnFailedSessionRead() throws Exception { ResourceResponse childResource = writeClient.createDocument(parentResource.getSelfLink(), documentDefinition, null, true).block(); logger.info("Created {} child resource", childResource.getResource().getResourceId()); - String token = childResource.getSessionToken().split(":")[0] + ":" + this.createSessionToken(SessionTokenHelper.parse(childResource.getSessionToken()), 100000000).convertToString(); + String token = childResource.getSessionToken().split(":")[0] + ":" + ConsistencyTestsBase.createSessionToken(SessionTokenHelper.parse(childResource.getSessionToken()), 100000000).convertToString(); FeedOptions feedOptions = new FeedOptions(); feedOptions.setPartitionKey(new PartitionKey(PartitionKeyInternal.Empty.toJson())); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ConsistencyTestsBase.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ConsistencyTestsBase.java index 83ac61b5e885..7d6c9032b11d 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ConsistencyTestsBase.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ConsistencyTestsBase.java @@ -77,10 +77,10 @@ void validateConsistentLSN() { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentDefinition.get("mypk"))); Document document = createDocument(this.writeClient, createdDatabase.getId(), createdCollection.getId(), documentDefinition); - ResourceResponse response = this.writeClient.deleteDocument(document.getSelfLink(), options).single().block(); + ResourceResponse response = this.writeClient.deleteDocument(document.getSelfLink(), options).single().block(); assertThat(response.getStatusCode()).isEqualTo(204); - long quorumAckedLSN = Long.parseLong((String) response.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); + long quorumAckedLSN = Long.parseLong(response.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); assertThat(quorumAckedLSN > 0).isTrue(); FailureValidator validator = new FailureValidator.Builder().statusCode(404).lsnGreaterThan(quorumAckedLSN).build(); Mono> readObservable = this.readClient.readDocument(document.getSelfLink(), options); @@ -92,10 +92,10 @@ void validateConsistentLSNAndQuorumAckedLSN() { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentDefinition.get("mypk"))); Document document = createDocument(this.writeClient, createdDatabase.getId(), createdCollection.getId(), documentDefinition); - ResourceResponse response = this.writeClient.deleteDocument(document.getSelfLink(), options).single().block(); + ResourceResponse response = this.writeClient.deleteDocument(document.getSelfLink(), options).single().block(); assertThat(response.getStatusCode()).isEqualTo(204); - long quorumAckedLSN = Long.parseLong((String) response.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); + long quorumAckedLSN = Long.parseLong(response.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); assertThat(quorumAckedLSN > 0).isTrue(); FailureValidator validator = new FailureValidator.Builder().statusCode(404).lsnGreaterThanEqualsTo(quorumAckedLSN).exceptionQuorumAckedLSNInNotNull().build(); @@ -765,6 +765,7 @@ private String getDifferentLSNToken(String token, long lsnDifferent) throws Exce return String.format("%s:%s", tokenParts[0], differentSessionToken.convertToString()); } + @SuppressWarnings({"unchecked", "rawtypes"}) public static ISessionToken createSessionToken(ISessionToken from, long globalLSN) throws Exception { // Creates session token with specified GlobalLSN if (from instanceof VectorSessionToken) { @@ -797,6 +798,7 @@ Document getDocumentDefinition() { return doc; } + @SuppressWarnings({"unchecked", "rawtypes"}) private boolean isSessionEqual(SessionContainer sessionContainer1, SessionContainer sessionContainer2) throws Exception { if (sessionContainer1 == null) { return false; diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/DocumentServiceRequestContextValidator.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/DocumentServiceRequestContextValidator.java index 7e0809d4620c..e8594d48c2ab 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/DocumentServiceRequestContextValidator.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/DocumentServiceRequestContextValidator.java @@ -12,14 +12,14 @@ public interface DocumentServiceRequestContextValidator { - static Builder builder() { - return new Builder(); + static Builder builder() { + return new Builder(); } void validate(T v); class Builder { - private List> validators = new ArrayList<>(); + private List> validators = new ArrayList<>(); public DocumentServiceRequestContextValidator build() { return new DocumentServiceRequestContextValidator() { @@ -27,7 +27,7 @@ public DocumentServiceRequestContextValidator build() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void validate(T v) { - for (DocumentServiceRequestContextValidator validator : validators) { + for (DocumentServiceRequestContextValidator validator : validators) { validator.validate(v); } } @@ -35,13 +35,13 @@ public void validate(T v) { } - public Builder add(DocumentServiceRequestContextValidator validator) { + public Builder add(DocumentServiceRequestContextValidator validator) { validators.add(validator); return this; } public Builder qurorumSelectedLSN(long quoriumSelectedLSN) { - add(new DocumentServiceRequestContextValidator() { + add(new DocumentServiceRequestContextValidator() { @Override public void validate(DocumentServiceRequestContext v) { assertThat(v.quorumSelectedLSN).isEqualTo(quoriumSelectedLSN); @@ -51,7 +51,7 @@ public void validate(DocumentServiceRequestContext v) { } public Builder globalCommittedSelectedLSN(long globalCommittedSelectedLSN) { - add(new DocumentServiceRequestContextValidator() { + add(new DocumentServiceRequestContextValidator() { @Override public void validate(DocumentServiceRequestContext v) { assertThat(v.globalCommittedSelectedLSN).isEqualTo(globalCommittedSelectedLSN); @@ -61,7 +61,7 @@ public void validate(DocumentServiceRequestContext v) { } public Builder storeResponses(List storeResponses) { - add(new DocumentServiceRequestContextValidator() { + add(new DocumentServiceRequestContextValidator() { @Override public void validate(DocumentServiceRequestContext v) { assertThat(v.storeResponses).isEqualTo(storeResponses); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/DocumentServiceRequestValidator.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/DocumentServiceRequestValidator.java index ca544d857fde..983e1f943995 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/DocumentServiceRequestValidator.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/DocumentServiceRequestValidator.java @@ -9,14 +9,14 @@ public interface DocumentServiceRequestValidator { - static Builder builder() { - return new Builder(); + static Builder builder() { + return new Builder(); } void validate(T v); class Builder { - private List> validators = new ArrayList<>(); + private List> validators = new ArrayList<>(); public DocumentServiceRequestValidator build() { return new DocumentServiceRequestValidator() { @@ -24,14 +24,14 @@ public DocumentServiceRequestValidator build() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void validate(T v) { - for (DocumentServiceRequestValidator validator : validators) { + for (DocumentServiceRequestValidator validator : validators) { validator.validate(v); } } }; } - public Builder add(DocumentServiceRequestValidator validator) { + public Builder add(DocumentServiceRequestValidator validator) { validators.add(validator); return this; } @@ -76,8 +76,8 @@ public void validate(T v) { return this; } - public Builder add(DocumentServiceRequestContextValidator validator) { - add(new DocumentServiceRequestValidator() { + public Builder add(DocumentServiceRequestContextValidator validator) { + add(new DocumentServiceRequestValidator() { @Override public void validate(RxDocumentServiceRequest request) { validator.validate(request.requestContext); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/FailureValidator.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/FailureValidator.java index eb1c151905af..83f9d96b1e05 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/FailureValidator.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/FailureValidator.java @@ -79,7 +79,7 @@ public void validate(Throwable t) { CosmosClientException cosmosClientException = (CosmosClientException) t; long exceptionQuorumAckedLSN = -1; if (cosmosClientException.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN) != null) { - exceptionQuorumAckedLSN = Long.parseLong((String) cosmosClientException.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); + exceptionQuorumAckedLSN = Long.parseLong(cosmosClientException.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); } assertThat(exceptionQuorumAckedLSN).isNotEqualTo(-1); @@ -312,7 +312,7 @@ public void validate(Throwable t) { return this; } - public Builder withRuntimeExceptionClass(Class k) { + public Builder withRuntimeExceptionClass(Class k) { validators.add(new FailureValidator() { @Override public void validate(Throwable t) { diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/FeedResponseListValidator.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/FeedResponseListValidator.java index 92f9f753811a..da4be07245db 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/FeedResponseListValidator.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/FeedResponseListValidator.java @@ -267,11 +267,12 @@ public void validate(List> feedList) { return this; } + @SuppressWarnings("unchecked") public Builder hasValidQueryMetrics(boolean shouldHaveMetrics) { validators.add(new FeedResponseListValidator() { @Override public void validate(List> feedList) { - for(FeedResponse feedPage: feedList) { + for(FeedResponse feedPage: feedList) { if (shouldHaveMetrics) { QueryMetrics queryMetrics = BridgeInternal.createQueryMetricsFromCollection(BridgeInternal.queryMetricsFromFeedResponse(feedPage).values()); assertThat(queryMetrics.getIndexHitDocumentCount()).isGreaterThanOrEqualTo(0); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ResourceResponseValidator.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ResourceResponseValidator.java index 559a06697aa6..59a9470c058f 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ResourceResponseValidator.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/ResourceResponseValidator.java @@ -26,8 +26,8 @@ public interface ResourceResponseValidator { - static Builder builder() { - return new Builder(); + static Builder builder() { + return new Builder<>(); } void validate(ResourceResponse resourceResponse); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/RetryUtilsTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/RetryUtilsTest.java index 8c1f485a7dac..77411d587789 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/RetryUtilsTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/RetryUtilsTest.java @@ -33,6 +33,7 @@ public class RetryUtilsTest { private StoreResponse storeResponse; @BeforeClass(groups = { "unit" }) + @SuppressWarnings({"unchecked", "rawtypes"}) public void before_RetryUtilsTest() throws Exception { retryPolicy = Mockito.mock(IRetryPolicy.class); request = Mockito.mock(RxDocumentServiceRequest.class); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/SessionContainerTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/SessionContainerTest.java index bb07ed2d45cb..0d80fc14c9fa 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/SessionContainerTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/SessionContainerTest.java @@ -90,7 +90,9 @@ public void setSessionToken_NoSessionTokenForPartitionKeyRangeId() throws Except respHeaders.put(HttpConstants.HttpHeaders.OWNER_ID, collectionRid); sessionContainer.setSessionToken(request1, resp.getResponseHeaders()); + @SuppressWarnings("unchecked") ConcurrentHashMap collectionNameToCollectionResourceId = (ConcurrentHashMap) FieldUtils.readField(sessionContainer, "collectionNameToCollectionResourceId", true); + @SuppressWarnings("unchecked") ConcurrentHashMap> collectionResourceIdToSessionTokens = (ConcurrentHashMap>) FieldUtils.readField(sessionContainer, "collectionResourceIdToSessionTokens", true); assertThat(collectionNameToCollectionResourceId).hasSize(1); assertThat(collectionResourceIdToSessionTokens).hasSize(1); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/SpyClientUnderTestFactory.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/SpyClientUnderTestFactory.java index 88790103eacf..e3e52cdba795 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/SpyClientUnderTestFactory.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/SpyClientUnderTestFactory.java @@ -86,7 +86,7 @@ RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, } protected void initRequestCapture() { - doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) { RxDocumentServiceRequest req = invocationOnMock.getArgumentAt(0, RxDocumentServiceRequest.class); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/StoreResponseBuilder.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/StoreResponseBuilder.java index 1c1442cf7c2b..62b4aa2898f7 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/StoreResponseBuilder.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/StoreResponseBuilder.java @@ -28,12 +28,12 @@ public StoreResponseBuilder() { } public StoreResponseBuilder withHeader(String key, String value) { - headerEntries.add(new AbstractMap.SimpleEntry(key, value)); + headerEntries.add(new AbstractMap.SimpleEntry<>(key, value)); return this; } public StoreResponseBuilder withLSN(long lsn) { - headerEntries.add(new AbstractMap.SimpleEntry(WFConstants.BackendHeaders.LSN, Long.toString(lsn))); + headerEntries.add(new AbstractMap.SimpleEntry<>(WFConstants.BackendHeaders.LSN, Long.toString(lsn))); return this; } @@ -43,42 +43,42 @@ public StoreResponseBuilder withRequestCharge(BigDecimal requestCharge) { } public StoreResponseBuilder withRequestCharge(double requestCharge) { - headerEntries.add(new AbstractMap.SimpleEntry(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge))); + headerEntries.add(new AbstractMap.SimpleEntry<>(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge))); return this; } public StoreResponseBuilder withLocalLSN(long localLsn) { - headerEntries.add(new AbstractMap.SimpleEntry(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(localLsn))); + headerEntries.add(new AbstractMap.SimpleEntry<>(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(localLsn))); return this; } public StoreResponseBuilder withPartitionKeyRangeId(String partitionKeyRangeId) { - headerEntries.add(new AbstractMap.SimpleEntry(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId)); + headerEntries.add(new AbstractMap.SimpleEntry<>(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId)); return this; } public StoreResponseBuilder withItemLocalLSN(long itemLocalLsn) { - headerEntries.add(new AbstractMap.SimpleEntry(WFConstants.BackendHeaders.ITEM_LOCAL_LSN, Long.toString(itemLocalLsn))); + headerEntries.add(new AbstractMap.SimpleEntry<>(WFConstants.BackendHeaders.ITEM_LOCAL_LSN, Long.toString(itemLocalLsn))); return this; } public StoreResponseBuilder withQuorumAckecdLsn(long quorumAckecdLsn) { - headerEntries.add(new AbstractMap.SimpleEntry(WFConstants.BackendHeaders.QUORUM_ACKED_LSN, Long.toString(quorumAckecdLsn))); + headerEntries.add(new AbstractMap.SimpleEntry<>(WFConstants.BackendHeaders.QUORUM_ACKED_LSN, Long.toString(quorumAckecdLsn))); return this; } public StoreResponseBuilder withQuorumAckecdLocalLsn(long quorumAckecdLocalLsn) { - headerEntries.add(new AbstractMap.SimpleEntry(WFConstants.BackendHeaders.QUORUM_ACKED_LOCAL_LSN, Long.toString(quorumAckecdLocalLsn))); + headerEntries.add(new AbstractMap.SimpleEntry<>(WFConstants.BackendHeaders.QUORUM_ACKED_LOCAL_LSN, Long.toString(quorumAckecdLocalLsn))); return this; } public StoreResponseBuilder withGlobalCommittedLsn(long globalCommittedLsn) { - headerEntries.add(new AbstractMap.SimpleEntry(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn))); + headerEntries.add(new AbstractMap.SimpleEntry<>(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn))); return this; } public StoreResponseBuilder withSessionToken(String sessionToken) { - headerEntries.add(new AbstractMap.SimpleEntry(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionToken)); + headerEntries.add(new AbstractMap.SimpleEntry<>(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionToken)); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/TestSuiteBase.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/TestSuiteBase.java index c875ed0c2242..1065200d3a73 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/TestSuiteBase.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/TestSuiteBase.java @@ -255,6 +255,7 @@ protected static void truncateCollection(DocumentCollection collection) { logger.info("Finished truncating collection {}.", collection.getId()); } + @SuppressWarnings("fallthrough") protected static void waitIfNeededForReplicasToCatchUp(Builder clientBuilder) { switch (clientBuilder.getDesiredConsistencyLevel()) { case EVENTUAL: @@ -866,6 +867,7 @@ static List parseDesiredConsistencies(String consistencies) { } } + @SuppressWarnings("fallthrough") static List allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List testConsistencies = new ArrayList<>(); switch (accountConsistency) { diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/AddressResolverTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/AddressResolverTest.java index b5646aac7d4d..3a1d670d2538 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/AddressResolverTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/AddressResolverTest.java @@ -310,7 +310,7 @@ private void initializeMocks( final Map addressesAfterRefresh = ObjectUtils.defaultIfNull(addressesAfterRefreshInitial, addressesBeforeRefresh); // Collection cache - MutableObject currentCollection = new MutableObject(collectionBeforeRefresh); + MutableObject currentCollection = new MutableObject<>(collectionBeforeRefresh); this.collectionCacheRefreshedCount = 0; Mockito.doAnswer(invocationOnMock -> { @@ -351,7 +351,9 @@ private void initializeMocks( CollectionRoutingMap previousValue = invocationOnMock.getArgumentAt(1, CollectionRoutingMap.class); return collectionRoutingMapCache.tryLookupAsync(collectionRid, previousValue, false, null); - }).when(this.collectionRoutingMapCache).tryLookupAsync(Mockito.anyString(), Mockito.any(CollectionRoutingMap.class), Mockito.anyMap()); + }).when(this.collectionRoutingMapCache).tryLookupAsync(Mockito.anyString(), + Mockito.any(CollectionRoutingMap.class), + Mockito.anyMapOf(String.class, Object.class)); // Refresh case Mockito.doAnswer(invocationOnMock -> { @@ -387,7 +389,10 @@ private void initializeMocks( } return Mono.error(new NotImplementedException("not mocked")); - }).when(this.collectionRoutingMapCache).tryLookupAsync(Mockito.anyString(), Mockito.any(CollectionRoutingMap.class), Mockito.anyBoolean(), Mockito.anyMap()); + }).when(this.collectionRoutingMapCache).tryLookupAsync(Mockito.anyString(), + Mockito.any(CollectionRoutingMap.class), + Mockito.anyBoolean(), + Mockito.anyMapOf(String.class, Object.class)); // Fabric Address Cache diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/AddressSelectorWrapper.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/AddressSelectorWrapper.java index 53d1c24f36e7..208ddefc5427 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/AddressSelectorWrapper.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/AddressSelectorWrapper.java @@ -187,20 +187,26 @@ public void verify(InvocationOnMock invocation) { VerifierBuilder resolveAllUriAsync_IncludePrimary(boolean primaryIncluded) { methodName(resolveAllUriAsync); - Condition alwaysTrue = new Condition(Predicates.alwaysTrue(), "no getCondition"); - Condition primaryIncludedCond = new Condition(Predicates.equalTo(primaryIncluded), String.format("%b (primaryIncluded)", primaryIncluded)); + Condition alwaysTrue = new Condition<>(Predicates.alwaysTrue(), "no getCondition"); + Condition primaryIncludedCond = new Condition<>(Predicates.equalTo(primaryIncluded), String.format("%b (primaryIncluded)", primaryIncluded)); - resolveAllUriAsync(alwaysTrue, primaryIncludedCond, alwaysTrue); + resolveAllUriAsync( + new Condition<>(Predicates.alwaysTrue(), "no condition"), + primaryIncludedCond, + alwaysTrue); return this; } VerifierBuilder resolveAllUriAsync_ForceRefresh(boolean forceRefresh) { methodName(resolveAllUriAsync); - Condition alwaysTrue = new Condition(Predicates.alwaysTrue(), "no condition"); - Condition forceRefreshCond = new Condition(Predicates.equalTo(forceRefresh), String.format("%b (forceRefresh)", forceRefresh)); + Condition alwaysTrue = new Condition<>(Predicates.alwaysTrue(), "no condition"); + Condition forceRefreshCond = new Condition<>(Predicates.equalTo(forceRefresh), String.format("%b (forceRefresh)", forceRefresh)); - resolveAllUriAsync(alwaysTrue, alwaysTrue, forceRefreshCond); + resolveAllUriAsync( + new Condition<>(Predicates.alwaysTrue(), "no condition"), + alwaysTrue, + forceRefreshCond); return this; } } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ConsistencyWriterTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ConsistencyWriterTest.java index 7a79959d242a..911349c2203c 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ConsistencyWriterTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ConsistencyWriterTest.java @@ -165,7 +165,7 @@ public void timeout1() throws Exception { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); Mockito.doReturn(true).when(timeoutHelper).isElapsed(); ConsistencyWriter spyConsistencyWriter = Mockito.spy(this.consistencyWriter); - TestSubscriber subscriber = new TestSubscriber(); + TestSubscriber subscriber = new TestSubscriber<>(); spyConsistencyWriter.writeAsync(Mockito.mock(RxDocumentServiceRequest.class), timeoutHelper, false) .subscribe(subscriber); @@ -182,7 +182,7 @@ public void timeout2() throws Exception { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); Mockito.doReturn(false).doReturn(true).when(timeoutHelper).isElapsed(); ConsistencyWriter spyConsistencyWriter = Mockito.spy(this.consistencyWriter); - TestSubscriber subscriber = new TestSubscriber(); + TestSubscriber subscriber = new TestSubscriber<>(); spyConsistencyWriter.writeAsync(Mockito.mock(RxDocumentServiceRequest.class), timeoutHelper, false) .subscribe(subscriber); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/DCDocumentCrudTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/DCDocumentCrudTest.java index 0f78987ad92e..5dc358681f7f 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/DCDocumentCrudTest.java @@ -192,7 +192,7 @@ public void upsert() throws Exception { String propValue = "hello"; BridgeInternal.setProperty(document, propName, propValue); - ResourceResponseValidator validator = ResourceResponseValidator.builder() + ResourceResponseValidator validator = ResourceResponseValidator.builder() .withProperty(propName, propValue) .build(); validateSuccess(client.upsertDocument(getCollectionLink(), document, options, false), validator, TIMEOUT); @@ -237,11 +237,12 @@ public void crossPartitionQuery() { private void validateNoStoredProcExecutionOperationThroughGateway() { // this validates that Document related requests don't go through gateway - DocumentServiceRequestValidator validateResourceTypesSentToGateway = DocumentServiceRequestValidator.builder() - .resourceTypeIn(ResourceType.DatabaseAccount, - ResourceType.Database, - ResourceType.DocumentCollection, - ResourceType.PartitionKeyRange) + DocumentServiceRequestValidator validateResourceTypesSentToGateway + = DocumentServiceRequestValidator.builder() + .resourceTypeIn(ResourceType.DatabaseAccount, + ResourceType.Database, + ResourceType.DocumentCollection, + ResourceType.PartitionKeyRange) .build(); // validate that all gateway captured requests are non document resources @@ -252,11 +253,12 @@ private void validateNoStoredProcExecutionOperationThroughGateway() { private void validateNoDocumentOperationThroughGateway() { // this validates that Document related requests don't go through gateway - DocumentServiceRequestValidator validateResourceTypesSentToGateway = DocumentServiceRequestValidator.builder() - .resourceTypeIn(ResourceType.DatabaseAccount, - ResourceType.Database, - ResourceType.DocumentCollection, - ResourceType.PartitionKeyRange) + DocumentServiceRequestValidator validateResourceTypesSentToGateway + = DocumentServiceRequestValidator.builder() + .resourceTypeIn(ResourceType.DatabaseAccount, + ResourceType.Database, + ResourceType.DocumentCollection, + ResourceType.PartitionKeyRange) .build(); // validate that all gateway captured requests are non document resources @@ -267,11 +269,12 @@ private void validateNoDocumentOperationThroughGateway() { private void validateNoDocumentQueryOperationThroughGateway() { // this validates that Document related requests don't go through gateway - DocumentServiceRequestValidator validateResourceTypesSentToGateway = DocumentServiceRequestValidator.builder() - .resourceTypeIn(ResourceType.DatabaseAccount, - ResourceType.Database, - ResourceType.DocumentCollection, - ResourceType.PartitionKeyRange) + DocumentServiceRequestValidator validateResourceTypesSentToGateway + = DocumentServiceRequestValidator.builder() + .resourceTypeIn(ResourceType.DatabaseAccount, + ResourceType.Database, + ResourceType.DocumentCollection, + ResourceType.PartitionKeyRange) .build(); // validate that all gateway captured requests are non document resources diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ExceptionBuilder.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ExceptionBuilder.java index 42922009730d..d5cb8cc330ff 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ExceptionBuilder.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ExceptionBuilder.java @@ -3,7 +3,6 @@ package com.azure.cosmos.implementation.directconnectivity; -import com.azure.cosmos.CosmosClientException; import com.azure.cosmos.implementation.GoneException; import com.azure.cosmos.implementation.InvalidPartitionException; import com.azure.cosmos.implementation.PartitionIsMigratingException; @@ -16,7 +15,7 @@ import java.util.Map; import java.util.stream.Collectors; -public class ExceptionBuilder { +public class ExceptionBuilder { private Integer status; private List> headerEntries; private String message; @@ -30,7 +29,7 @@ public ExceptionBuilder() { } public ExceptionBuilder withHeader(String key, String value) { - headerEntries.add(new AbstractMap.SimpleEntry(key, value)); + headerEntries.add(new AbstractMap.SimpleEntry<>(key, value)); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GatewayAddressCacheTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GatewayAddressCacheTest.java index b0f3dace29c1..6e6398a5c6e0 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GatewayAddressCacheTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GatewayAddressCacheTest.java @@ -121,6 +121,7 @@ public void getServerAddressesViaGateway(List partitionKeyRangeIds, } @Test(groups = { "direct" }, dataProvider = "protocolProvider", timeOut = TIMEOUT) + @SuppressWarnings({"unchecked", "rawtypes"}) public void getMasterAddressesViaGatewayAsync(Protocol protocol) throws Exception { Configs configs = ConfigsBuilder.instance().withProtocol(protocol).build(); // ask gateway for the addresses @@ -319,6 +320,7 @@ public void tryGetAddresses_ForDataPartitions_ForceRefresh( @Test(groups = { "direct" }, dataProvider = "openAsyncTargetAndTargetPartitionsKeyRangeAndCollectionLinkParams", timeOut = TIMEOUT) + @SuppressWarnings({"unchecked", "rawtypes"}) public void tryGetAddresses_ForDataPartitions_Suboptimal_Refresh( List allPartitionKeyRangeIds, String partitionKeyRangeId, @@ -365,13 +367,13 @@ public void tryGetAddresses_ForDataPartitions_Suboptimal_Refresh( GatewayAddressCache spyCache = Mockito.spy(origCache); final AtomicInteger fetchCounter = new AtomicInteger(0); - Mockito.doAnswer(new Answer() { + Mockito.doAnswer(new Answer>>() { @Override public Mono> answer(InvocationOnMock invocationOnMock) throws Throwable { RxDocumentServiceRequest req = invocationOnMock.getArgumentAt(0, RxDocumentServiceRequest.class); String collectionRid = invocationOnMock.getArgumentAt(1, String.class); - List partitionKeyRangeIds = invocationOnMock.getArgumentAt(2, List.class); + List partitionKeyRangeIds = invocationOnMock.getArgumentAt(2, List.class); boolean forceRefresh = invocationOnMock.getArgumentAt(3, Boolean.class); int cnt = fetchCounter.getAndIncrement(); @@ -392,7 +394,7 @@ public Mono> answer(InvocationOnMock invocationOnMock) throws Thro forceRefresh); } }).when(spyCache).getServerAddressesViaGatewayAsync(Matchers.any(RxDocumentServiceRequest.class), Matchers.anyString(), - Matchers.anyList(), Matchers.anyBoolean()); + Matchers.anyListOf(String.class), Matchers.anyBoolean()); httpClientWrapper.capturedRequests.clear(); @@ -586,7 +588,7 @@ public void tryGetAddresses_SuboptimalMasterPartition_NotStaleEnough_NoRefresh() GatewayAddressCache spyCache = Mockito.spy(origCache); final AtomicInteger getMasterAddressesViaGatewayAsyncInvocation = new AtomicInteger(0); - Mockito.doAnswer(new Answer() { + Mockito.doAnswer(new Answer>>() { @Override public Mono> answer(InvocationOnMock invocationOnMock) throws Throwable { @@ -623,7 +625,7 @@ public Mono> answer(InvocationOnMock invocationOnMock) throws Thro null); } }).when(spyCache).getMasterAddressesViaGatewayAsync(Matchers.any(RxDocumentServiceRequest.class), Matchers.any(ResourceType.class), Matchers.anyString(), - Matchers.anyString(), Matchers.anyBoolean(), Matchers.anyBoolean(), Matchers.anyMap()); + Matchers.anyString(), Matchers.anyBoolean(), Matchers.anyBoolean(), Matchers.anyMapOf(String.class, Object.class)); RxDocumentServiceRequest req = @@ -676,7 +678,7 @@ public void tryGetAddresses_SuboptimalMasterPartition_Stale_DoRefresh() throws E GatewayAddressCache spyCache = Mockito.spy(origCache); final AtomicInteger getMasterAddressesViaGatewayAsyncInvocation = new AtomicInteger(0); - Mockito.doAnswer(new Answer() { + Mockito.doAnswer(new Answer>>() { @Override public Mono> answer(InvocationOnMock invocationOnMock) throws Throwable { @@ -715,7 +717,7 @@ public Mono> answer(InvocationOnMock invocationOnMock) throws Thro null); } }).when(spyCache).getMasterAddressesViaGatewayAsync(Matchers.any(RxDocumentServiceRequest.class), Matchers.any(ResourceType.class), Matchers.anyString(), - Matchers.anyString(), Matchers.anyBoolean(), Matchers.anyBoolean(), Matchers.anyMap()); + Matchers.anyString(), Matchers.anyBoolean(), Matchers.anyBoolean(), Matchers.anyMapOf(String.class, Object.class)); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Database, diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolverTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolverTest.java index e25b9a297acb..095a8832f73a 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolverTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalAddressResolverTest.java @@ -74,13 +74,13 @@ public void before_GlobalAddressResolverTest() throws Exception { readEndPointList.add(urlforRead1); readEndPointList.add(urlforRead2); readEndPointList.add(urlforRead3); - UnmodifiableList readList = new UnmodifiableList(readEndPointList); + UnmodifiableList readList = new UnmodifiableList<>(readEndPointList); List writeEndPointList = new ArrayList<>(); writeEndPointList.add(urlforWrite1); writeEndPointList.add(urlforWrite2); writeEndPointList.add(urlforWrite3); - UnmodifiableList writeList = new UnmodifiableList(writeEndPointList); + UnmodifiableList writeList = new UnmodifiableList<>(writeEndPointList); Mockito.when(endpointManager.getReadEndpoints()).thenReturn(readList); Mockito.when(endpointManager.getWriteEndpoints()).thenReturn(writeList); @@ -151,7 +151,7 @@ public void openAsync() throws Exception { Mockito.when(routingMapProvider.tryLookupAsync(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(collectionRoutingMapSingle); List ranges = new ArrayList<>(); - for (PartitionKeyRange partitionKeyRange : (List) collectionRoutingMap.getOrderedPartitionKeyRanges()) { + for (PartitionKeyRange partitionKeyRange : collectionRoutingMap.getOrderedPartitionKeyRanges()) { PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(documentCollection.getResourceId(), partitionKeyRange.getId()); ranges.add(partitionKeyRangeIdentity); } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalEndPointManagerTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalEndPointManagerTest.java index cc2fc4f5bb69..72cfe5b448b8 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalEndPointManagerTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/GlobalEndPointManagerTest.java @@ -292,7 +292,9 @@ private Map getAvailableWriteEndpointByLocation(LocationCache locat Field availableReadEndpointByLocationField = DatabaseAccountLocationsInfoClass.getDeclaredField("availableReadEndpointByLocation"); availableReadEndpointByLocationField.setAccessible(true); - return (Map) availableWriteEndpointByLocationField.get(locationInfo); + @SuppressWarnings("unchecked") + Map map = (Map) availableWriteEndpointByLocationField.get(locationInfo); + return map; } private Map getAvailableReadEndpointByLocation(LocationCache locationCache) throws Exception { @@ -304,7 +306,9 @@ private Map getAvailableReadEndpointByLocation(LocationCache locati Field availableReadEndpointByLocationField = DatabaseAccountLocationsInfoClass.getDeclaredField("availableReadEndpointByLocation"); availableReadEndpointByLocationField.setAccessible(true); - return (Map) availableReadEndpointByLocationField.get(locationInfo); + @SuppressWarnings("unchecked") + Map map = (Map) availableReadEndpointByLocationField.get(locationInfo); + return map; } private AtomicBoolean getIsRefreshing(GlobalEndpointManager globalEndPointManager) throws Exception { diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/MurmurHash3_32Test.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/MurmurHash3_32Test.java index 7925294fa0d8..240169b9559e 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/MurmurHash3_32Test.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/MurmurHash3_32Test.java @@ -30,7 +30,7 @@ public void before_MurmurHash3_32Test() { @Test(groups = "unit") public void murmurHash3_32_EmptyByteArray() { byte[] byteArray = new byte[0]; - int actualHash = murmurHash3_32.hash(byteArray, byteArray.length, 0); + int actualHash = MurmurHash3_32.hash(byteArray, byteArray.length, 0); HashFunction googleMurmur3_32 = Hashing.murmur3_32(0); int expectedHash = googleMurmur3_32.hashBytes(byteArray).asInt(); @@ -41,7 +41,7 @@ public void murmurHash3_32_EmptyByteArray() { @Test(groups = "unit") public void murmurHash3_32_String() { byte[] byteArray = new String("test").getBytes(Charset.forName("UTF-8")); - int actualHash = murmurHash3_32.hash(byteArray, byteArray.length, 0); + int actualHash = MurmurHash3_32.hash(byteArray, byteArray.length, 0); HashFunction googleMurmur3_32 = Hashing.murmur3_32(0); int expectedHash = googleMurmur3_32.hashBytes(byteArray).asInt(); @@ -54,7 +54,7 @@ public void murmurHash3_32_NonLatin() throws UnsupportedEncodingException { String nonLatin = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяабвгдеёжзийклмнопрстуфхцчшщъыьэюяабвгдеёжзийклмнопрстуфхцчшщъыьэюяабвгдеёжзийклмнопрстуфхцчшщъыьэюя"; for(int i = 0; i < nonLatin.length() + 1; i++) { byte[] byteArray = nonLatin.substring(0, i).getBytes("UTF-8"); - int actualHash = murmurHash3_32.hash(byteArray, byteArray.length, 0); + int actualHash = MurmurHash3_32.hash(byteArray, byteArray.length, 0); HashFunction googleMurmur3_32 = Hashing.murmur3_32(0); int expectedHash = googleMurmur3_32.hashBytes(byteArray).asInt(); @@ -66,7 +66,7 @@ public void murmurHash3_32_NonLatin() throws UnsupportedEncodingException { @Test(groups = "unit") public void murmurHash3_32_ZeroByteArray() { byte[] byteArray = new byte[3]; - int actualHash = murmurHash3_32.hash(byteArray, byteArray.length, 0); + int actualHash = MurmurHash3_32.hash(byteArray, byteArray.length, 0); HashFunction googleMurmur3_32 = Hashing.murmur3_32(0); int expectedHash = googleMurmur3_32.hashBytes(byteArray).asInt(); @@ -79,7 +79,7 @@ public void murmurHash3_32_RandomBytesOfAllSizes() { for(int i = 0; i < 1000; i++) { byte[] byteArray = randomBytes(i); - int actualHash = murmurHash3_32.hash(byteArray, byteArray.length, 0); + int actualHash = MurmurHash3_32.hash(byteArray, byteArray.length, 0); HashFunction googleMurmur3_32 = Hashing.murmur3_32(0); int expectedHash = googleMurmur3_32.hashBytes(byteArray).asInt(); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/QuorumReaderTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/QuorumReaderTest.java index e39006feb13f..823801c9e8cb 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/QuorumReaderTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/QuorumReaderTest.java @@ -141,6 +141,7 @@ public Object[][] readStrong_RequestBarrierArgProvider() { } @Test(groups = "unit", dataProvider = "readStrong_RequestBarrierArgProvider") + @SuppressWarnings({"unchecked", "rawtypes"}) public void readStrong_OnlySecondary_RequestBarrier_Success(int numberOfBarrierRequestTillCatchUp) { // scenario: we get lsn l1, l2 where l1 > l2 // we do barrier request and send it to all replicas till we have two replicas with at least l1 lsn @@ -285,6 +286,7 @@ public Object[][] readStrong_SecondaryReadBarrierExhausted_ReadBarrierOnPrimary_ } @Test(groups = "unit", dataProvider = "readStrong_SecondaryReadBarrierExhausted_ReadBarrierOnPrimary_SuccessArgProvider") + @SuppressWarnings({"unchecked", "rawtypes"}) public void readStrong_SecondaryReadBarrierExhausted_ReadBarrierOnPrimary_Success(int numberOfHeadBarriersWithPrimaryIncludedTillQuorumMet) { // scenario: we exhaust all barrier request retries on secondaries // after that we start barrier requests including the primary @@ -445,6 +447,7 @@ public void readStrong_SecondaryReadBarrierExhausted_ReadBarrierOnPrimary_Succes } @Test(groups = "unit") + @SuppressWarnings({"unchecked", "rawtypes"}) public void readStrong_QuorumNotSelected_ReadPrimary() { // scenario: attempts to read from secondaries, // only one secondary is available so ends in QuorumNotSelected State diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ReflectionUtils.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ReflectionUtils.java index f78e7000fedb..9dbdc312ffcd 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ReflectionUtils.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/ReflectionUtils.java @@ -31,6 +31,8 @@ private static void set(Object object, T newValue, String fieldName) { } } + @SuppressWarnings("unchecked") + // Note: @moderakh @kushagraThapar - klass is not used but still casting to T private static T get(Class klass, Object object, String fieldName) { try { return (T) FieldUtils.readField(object, fieldName, true); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/StoreReaderDotNetTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/StoreReaderDotNetTest.java index d86c1d8a47af..b38d6fb06c33 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/StoreReaderDotNetTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/StoreReaderDotNetTest.java @@ -560,6 +560,7 @@ public static void validateException(Mono single, * StoreClient uses ReplicatedResourceClient uses ConsistencyReader uses QuorumReader uses StoreReader uses TransportClient uses RntbdConnection */ @Test(groups = "unit", enabled = false) + @SuppressWarnings("unchecked") public void storeClient() throws URISyntaxException { // create a real document service request (with auth token level = god) RxDocumentServiceRequest entity = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); @@ -647,6 +648,7 @@ public void storeClient() throws URISyntaxException { * test consistency writer for global strong */ @Test(groups = "unit") + @SuppressWarnings("unchecked") public void globalStrongConsistentWrite() { // create a real document service request (with auth token level = god) RxDocumentServiceRequest entity = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document); @@ -733,6 +735,7 @@ public void globalStrongConsistentWrite() { * Mocking Consistency */ @Test(groups = "unit", priority = 1) + @SuppressWarnings({"unchecked", "rawtypes"}) public void globalStrongConsistency() { // create a real document service request (with auth token level = god) RxDocumentServiceRequest entity = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/StoreResponseValidator.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/StoreResponseValidator.java index 8ecf2c1cb70d..1d5aee4f0bee 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/StoreResponseValidator.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/StoreResponseValidator.java @@ -2,7 +2,6 @@ // Licensed under the MIT License. package com.azure.cosmos.implementation.directconnectivity; -import com.azure.cosmos.models.Resource; import com.azure.cosmos.implementation.HttpConstants; import org.assertj.core.api.Condition; @@ -20,13 +19,12 @@ public static Builder create() { return new Builder(); } - public class Builder { + public class Builder { private List validators = new ArrayList<>(); public StoreResponseValidator build() { return new StoreResponseValidator() { - @SuppressWarnings({"rawtypes", "unchecked"}) @Override public void validate(StoreResponse resp) { for (StoreResponseValidator validator : validators) { diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/TransportClientWrapper.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/TransportClientWrapper.java index e64d774588be..61e11fefe17d 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/TransportClientWrapper.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/directconnectivity/TransportClientWrapper.java @@ -96,7 +96,7 @@ public static ReplicaResponseBuilder replicaResponseBuilder() { } class ReplicaResponseBuilder implements Builder { - Map responseFunctionDictionary = new HashMap<>(); + Map> responseFunctionDictionary = new HashMap<>(); public ReplicaResponseBuilder addReplica(Uri replicaURI, Function2WithCheckedException invocationNumberToStoreResponse) { @@ -118,7 +118,8 @@ public TransportClientWrapper build() { i.incrementAndGet(); Uri physicalUri = invocation.getArgumentAt(0, Uri.class); RxDocumentServiceRequest request = invocation.getArgumentAt(1, RxDocumentServiceRequest.class); - Function2WithCheckedException function = responseFunctionDictionary.get(physicalUri); + Function2WithCheckedException function + = responseFunctionDictionary.get(physicalUri); if (function == null) { valid.set(false); return Mono.error(new IllegalStateException("no registered function for replica " + physicalUri)); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/query/DocumentProducerTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/query/DocumentProducerTest.java index 9b102904990a..73170d62b35a 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/query/DocumentProducerTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/query/DocumentProducerTest.java @@ -304,7 +304,7 @@ public void simple() { targetRange, collectionLink, () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), Document.class, null, initialPageSize, initialContinuationToken, top); - TestSubscriber subscriber = new TestSubscriber<>(); + TestSubscriber.DocumentProducerFeedResponse> subscriber = new TestSubscriber<>(); documentProducer.produceAsync().subscribe(subscriber); subscriber.awaitTerminalEvent(); @@ -362,7 +362,7 @@ public void retries() { targetRange, collectionLink, () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), Document.class, null, initialPageSize, initialContinuationToken, top); - TestSubscriber subscriber = new TestSubscriber<>(); + TestSubscriber.DocumentProducerFeedResponse> subscriber = new TestSubscriber<>(); documentProducer.produceAsync().subscribe(subscriber); subscriber.awaitTerminalEvent(); @@ -427,7 +427,7 @@ public void retriesExhausted() { targetRange, collectionRid, () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), Document.class, null, initialPageSize, initialContinuationToken, top); - TestSubscriber subscriber = new TestSubscriber<>(); + TestSubscriber.DocumentProducerFeedResponse> subscriber = new TestSubscriber<>(); documentProducer.produceAsync().subscribe(subscriber); subscriber.awaitTerminalEvent(); @@ -494,7 +494,7 @@ private List> mockFeedResponsesPartiallySorted(String par rfb.withContinuationToken("cp:" + uuid + ":" + i); } - FeedResponse resp = rfb.build(); + FeedResponse resp = rfb.build(); responses.add(resp); } return responses; @@ -517,12 +517,13 @@ private int getLastValueInAsc(int initialValue, List> res } } + @SuppressWarnings("unchecked") private IDocumentQueryClient mockQueryClient(List replacementRanges) { IDocumentQueryClient client = Mockito.mock(IDocumentQueryClient.class); RxPartitionKeyRangeCache cache = Mockito.mock(RxPartitionKeyRangeCache.class); doReturn(cache).when(client).getPartitionKeyRangeCache(); doReturn(Mono.just(new Utils.ValueHolder<>(replacementRanges))).when(cache). - tryGetOverlappingRangesAsync(anyString(), any(Range.class), anyBoolean(), Matchers.anyMap()); + tryGetOverlappingRangesAsync(anyString(), any(Range.class), anyBoolean(), Matchers.anyMapOf(String.class, Object.class)); return client; } @@ -701,7 +702,7 @@ static abstract class RequestExecutor implements Function invocationResult; Exception failureResult; public CapturedInvocation(RxDocumentServiceRequest request, Exception ex) { @@ -764,7 +765,7 @@ class Response { FeedResponse invocationResult; Exception failureResult; - public Response(FeedResponse invocationResult) { + public Response(FeedResponse invocationResult) { this.invocationResult = invocationResult; } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/query/FeedResponseBuilder.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/query/FeedResponseBuilder.java index b554a919bb3b..64c7f26f329b 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/query/FeedResponseBuilder.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/query/FeedResponseBuilder.java @@ -45,8 +45,12 @@ public FeedResponseBuilder withResults(List results) { return this; } - public FeedResponseBuilder withResults(T... results) { - this.results = Arrays.asList(results); + + // https://stackoverflow.com/a/47949197 + @SafeVarargs + @SuppressWarnings("varargs") + public final FeedResponseBuilder withResults(T... results) { + this.results = Arrays.asList(results); return this; } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/InMemoryCollectionRoutingMapTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/InMemoryCollectionRoutingMapTest.java index 97783295312c..4b611fedb84d 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/InMemoryCollectionRoutingMapTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/InMemoryCollectionRoutingMapTest.java @@ -118,6 +118,7 @@ public void incompleteRoutingMap() { } @Test(groups = {"unit"}) + @SuppressWarnings({"unchecked", "rawtypes"}) public void goneRanges() { CollectionRoutingMap routingMap = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap( ImmutableList.of( @@ -135,33 +136,33 @@ public void goneRanges() { assertThat(routingMap.IsGone("4")).isFalse(); assertThat(routingMap.IsGone("100")).isFalse(); } - + @Test(groups = {"unit"}) public void tryCombineRanges() { CollectionRoutingMap routingMap = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap( - ImmutableList.of( - new ImmutablePair( + ImmutableList.>of( + new ImmutablePair<>( new PartitionKeyRange( "2", "0000000050", "0000000070"), null), - new ImmutablePair( + new ImmutablePair<>( new PartitionKeyRange( "0", "", "0000000030"), null), - new ImmutablePair( + new ImmutablePair<>( new PartitionKeyRange( "1", "0000000030", "0000000050"), null), - new ImmutablePair( + new ImmutablePair<>( new PartitionKeyRange( "3", "0000000070", @@ -170,8 +171,8 @@ public void tryCombineRanges() { ), StringUtils.EMPTY); CollectionRoutingMap newRoutingMap = routingMap.tryCombine( - ImmutableList.of( - new ImmutablePair( + ImmutableList.>of( + new ImmutablePair<>( new PartitionKeyRange( "4", "", @@ -180,7 +181,7 @@ public void tryCombineRanges() { ), null), - new ImmutablePair( + new ImmutablePair<>( new PartitionKeyRange( "5", "0000000010", @@ -193,8 +194,8 @@ public void tryCombineRanges() { assertThat(newRoutingMap).isNotNull(); newRoutingMap = routingMap.tryCombine( - ImmutableList.of( - new ImmutablePair( + ImmutableList.>of( + new ImmutablePair<>( new PartitionKeyRange( "6", "", @@ -203,7 +204,7 @@ public void tryCombineRanges() { ), null), - new ImmutablePair( + new ImmutablePair<>( new PartitionKeyRange( "7", "0000000005", @@ -212,7 +213,7 @@ public void tryCombineRanges() { ), null), - new ImmutablePair( + new ImmutablePair<>( new PartitionKeyRange( "8", "0000000010", @@ -221,7 +222,7 @@ public void tryCombineRanges() { ), null), - new ImmutablePair( + new ImmutablePair<>( new PartitionKeyRange( "9", "0000000015", @@ -234,8 +235,8 @@ public void tryCombineRanges() { assertThat(newRoutingMap).isNotNull(); newRoutingMap = routingMap.tryCombine( - ImmutableList.of( - new ImmutablePair( + ImmutableList.>of( + new ImmutablePair<>( new PartitionKeyRange( "10", "", diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/LocationCacheTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/LocationCacheTest.java index 594b92794e53..de3c4553aa4c 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/LocationCacheTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/LocationCacheTest.java @@ -330,7 +330,7 @@ private void validateGlobalEndpointLocationCacheRefreshAsync() throws Exception IntStream.range(0, 10) .mapToObj(index -> this.endpointManager.refreshLocationAsync(null, false)) .collect(Collectors.toList()); - for (Mono completable : list) { + for (Mono completable : list) { completable.block(); } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/RoutingMapProviderHelperTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/RoutingMapProviderHelperTest.java index b94014719d6e..37af9fc9dbd3 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/RoutingMapProviderHelperTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/implementation/routing/RoutingMapProviderHelperTest.java @@ -154,7 +154,7 @@ public String apply(PartitionKeyRange range) { new PartitionKeyRange("6", "0040", "FF")); Mono> listSingle = Mono.just(rangeList); - Map> resultMap = new HashMap<>(); + Map, List> resultMap = new HashMap<>(); resultMap.put(new Range<>("000D", "0012", true, false), Collections.singletonList(new PartitionKeyRange("2", "000D", "0012"))); @@ -164,12 +164,13 @@ public String apply(PartitionKeyRange range) { Collections.singletonList(new PartitionKeyRange("4", "0015", "00120"))); Mockito.doAnswer(invocationOnMock -> { + @SuppressWarnings("rawtypes") Range range = invocationOnMock.getArgumentAt(1, Range.class); return Mono.just(new Utils.ValueHolder<>(resultMap.get(range))); }).when(routingMapProviderMock).tryGetOverlappingRangesAsync(Matchers.anyString(), Matchers.any(), Matchers.anyBoolean(), - Matchers.anyMap()); + Matchers.anyMapOf(String.class, Object.class)); Mono> overlappingRanges; overlappingRanges = RoutingMapProviderHelper.getOverlappingRanges(routingMapProviderMock, diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/models/CosmosPartitionKeyTests.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/models/CosmosPartitionKeyTests.java index 28cbdb20b531..23e930d90c61 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/models/CosmosPartitionKeyTests.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/models/CosmosPartitionKeyTests.java @@ -244,7 +244,7 @@ public void nonPartitionedCollectionOperations() throws Exception { .build(); validateQuerySuccess(queryFlux.byPage(), queryValidator); CosmosItemResponseValidator deleteResponseValidator; - Mono deleteMono = + Mono> deleteMono = createdContainer.deleteItem(upsertedItemId, PartitionKey.NONE); deleteResponseValidator = new CosmosItemResponseValidator.Builder>() diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/CollectionCrudTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/CollectionCrudTest.java index f27ab7043edc..84ff4652d8de 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/CollectionCrudTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/CollectionCrudTest.java @@ -330,7 +330,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { logger.info("Client 1 READ Document Latency {}", readDocumentResponse.getRequestLatency()); BridgeInternal.setProperty(document, "name", "New Updated Document"); - CosmosAsyncItemResponse upsertDocumentResponse = collection.upsertItem(document).block(); + CosmosAsyncItemResponse upsertDocumentResponse = collection.upsertItem(document).block(); logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.getCosmosResponseDiagnostics()); logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.getRequestLatency()); @@ -348,7 +348,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { readDocumentResponse = client1.getDatabase(dbId) .getContainer(collectionId) .readItem(newDocument.getId(), - new PartitionKey(newDocument.get("mypk")), + new PartitionKey(newDocument.get("mypk")), CosmosItemProperties.class) .block(); logger.info("Client 2 READ Document Client Side Request Statistics {}", readDocumentResponse.getCosmosResponseDiagnostics()); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/CosmosItemResponseValidator.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/CosmosItemResponseValidator.java index ad4e38dd968d..34c2eafecb14 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/CosmosItemResponseValidator.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/CosmosItemResponseValidator.java @@ -11,18 +11,20 @@ import static org.assertj.core.api.Assertions.assertThat; public interface CosmosItemResponseValidator { + @SuppressWarnings("rawtypes") void validate(CosmosAsyncItemResponse itemResponse); class Builder { private List validators = new ArrayList<>(); - public Builder withId(final String resourceId) { + public Builder withId(final String resourceId) { validators.add(new CosmosItemResponseValidator() { @Override + @SuppressWarnings("rawtypes") public void validate(CosmosAsyncItemResponse itemResponse) { assertThat(itemResponse.getItem()).isNotNull(); - // This could be validated for potential improvement by remove fromObject + // This could be validated for potential improvement by remove fromObject assertThat(CosmosItemProperties.fromObject(itemResponse.getItem()) .getId()).as("check Resource Id").isEqualTo(resourceId); } @@ -30,10 +32,11 @@ public void validate(CosmosAsyncItemResponse itemResponse) { return this; } - public Builder withProperty(String propertyName, String value) { + public Builder withProperty(String propertyName, String value) { validators.add(new CosmosItemResponseValidator() { @Override + @SuppressWarnings("rawtypes") public void validate(CosmosAsyncItemResponse itemResponse) { assertThat(itemResponse.getItem()).isNotNull(); assertThat(CosmosItemProperties.fromObject(itemResponse.getItem()) @@ -46,6 +49,7 @@ public void validate(CosmosAsyncItemResponse itemResponse) { public CosmosItemResponseValidator build() { return new CosmosItemResponseValidator() { @Override + @SuppressWarnings("rawtypes") public void validate(CosmosAsyncItemResponse itemResponse) { for (CosmosItemResponseValidator validator : validators) { validator.validate(itemResponse); @@ -54,15 +58,16 @@ public void validate(CosmosAsyncItemResponse itemResponse) { }; } - public Builder nullResource() { + public Builder nullResource() { validators.add(new CosmosItemResponseValidator() { @Override + @SuppressWarnings("rawtypes") public void validate(CosmosAsyncItemResponse itemResponse) { assertThat(itemResponse.getItem()).isNull(); } }); - return this; + return this; } } } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/DocumentCrudTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/DocumentCrudTest.java index bab913e8f55b..3c882a7fb3ce 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/DocumentCrudTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/DocumentCrudTest.java @@ -55,7 +55,7 @@ public void createDocument(String documentId) throws InterruptedException { CosmosItemProperties properties = getDocumentDefinition(documentId); Mono> createObservable = container.createItem(properties, new CosmosItemRequestOptions()); - + CosmosItemResponseValidator validator = new CosmosItemResponseValidator.Builder>() .withId(properties.getId()) @@ -63,7 +63,7 @@ public void createDocument(String documentId) throws InterruptedException { this.validateItemSuccess(createObservable, validator); } - + // TODO (DANOBLE) DocumentCrudTest::createLargeDocument fails in some environments // see https://github.com/Azure/azure-sdk-for-java/issues/6335 @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") @@ -100,7 +100,7 @@ public void createDocumentWithVeryLargePartitionKey(String documentId) throws In .withId(docDefinition.getId()) .withProperty("mypk", sb.toString()) .build(); - + this.validateItemSuccess(createObservable, validator); } @@ -159,7 +159,7 @@ public void readDocument(String documentId) throws InterruptedException { CosmosItemRequestOptions options = new CosmosItemRequestOptions(); Mono> readObservable = container.readItem(docDefinition.getId(), - new PartitionKey(docDefinition.get("mypk")), + new PartitionKey(docDefinition.get("mypk")), options, CosmosItemProperties.class); CosmosItemResponseValidator validator = @@ -221,10 +221,10 @@ public void deleteDocument(String documentId) throws InterruptedException { container.createItem(docDefinition, new CosmosItemRequestOptions()).block(); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - Mono deleteObservable = container.deleteItem(documentId, - new PartitionKey(docDefinition.get("mypk")), + Mono> deleteObservable = container.deleteItem(documentId, + new PartitionKey(docDefinition.get("mypk")), options); - + CosmosItemResponseValidator validator = new CosmosItemResponseValidator.Builder>() .nullResource() @@ -235,7 +235,7 @@ public void deleteDocument(String documentId) throws InterruptedException { waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono> readObservable = container.readItem(documentId, - new PartitionKey(docDefinition.get("mypk")), + new PartitionKey(docDefinition.get("mypk")), options, CosmosItemProperties.class); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateItemFailure(readObservable, notFoundValidator); @@ -249,7 +249,7 @@ public void deleteDocument_undefinedPK(String documentId) throws InterruptedExce container.createItem(docDefinition, new CosmosItemRequestOptions()).block(); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - Mono deleteObservable = container.deleteItem(documentId, + Mono> deleteObservable = container.deleteItem(documentId, PartitionKey.NONE, options); @@ -281,7 +281,7 @@ public void deleteDocument_DoesntExist(String documentId) throws InterruptedExce .block(); // delete again - Mono deleteObservable = container.deleteItem(documentId, + Mono> deleteObservable = container.deleteItem(documentId, PartitionKey.NONE, options);; @@ -330,7 +330,7 @@ public void upsertDocument_CreateDocument(String documentId) throws Throwable { new CosmosItemResponseValidator.Builder>() .withId(docDefinition.getId()) .build(); - + this.validateItemSuccess(upsertObservable, validator); } @@ -405,7 +405,7 @@ private void compareTestObjs(TestObject newTestObject, TestObject resultObject) static class TestObject { private String id; private String mypk; - private List> sgmts; + private List> sgmts; private String stringProp; public TestObject() { @@ -460,7 +460,7 @@ public void setStringProp(String stringProp) { this.stringProp = stringProp; } } - + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_DocumentCrudTest() { diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/OffsetLimitQueryTests.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/OffsetLimitQueryTests.java index d1e9633dd898..01393dec96c8 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/OffsetLimitQueryTests.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/OffsetLimitQueryTests.java @@ -163,6 +163,7 @@ private List queryWithContinuationTokens(String query, int testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); + @SuppressWarnings("unchecked") FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getContinuationToken(); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/OrderbyDocumentQueryTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/OrderbyDocumentQueryTest.java index 0bb9eb53049c..a6da8a5c7853 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/OrderbyDocumentQueryTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/OrderbyDocumentQueryTest.java @@ -102,7 +102,7 @@ public void queryDocumentsValidateContent(boolean qmEnabled) throws Exception { public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2' ORDER BY r.propInt"; FeedOptions options = new FeedOptions(); - + CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() @@ -125,7 +125,7 @@ public Object[][] sortOrder() { public void queryOrderBy(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r ORDER BY r.propInt %s", sortOrder); FeedOptions options = new FeedOptions(); - + int pageSize = 3; options.setMaxItemCount(pageSize); CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); @@ -153,7 +153,7 @@ public void queryOrderBy(String sortOrder) throws Exception { public void queryOrderByInt() throws Exception { String query = "SELECT * FROM r ORDER BY r.propInt"; FeedOptions options = new FeedOptions(); - + int pageSize = 3; options.setMaxItemCount(pageSize); CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); @@ -177,7 +177,7 @@ public void queryOrderByInt() throws Exception { public void queryOrderByString() throws Exception { String query = "SELECT * FROM r ORDER BY r.propStr"; FeedOptions options = new FeedOptions(); - + int pageSize = 3; options.setMaxItemCount(pageSize); CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); @@ -207,7 +207,7 @@ public Object[][] topValueParameter() { public void queryOrderWithTop(int topValue) throws Exception { String query = String.format("SELECT TOP %d * FROM r ORDER BY r.propInt", topValue); FeedOptions options = new FeedOptions(); - + int pageSize = 3; options.setMaxItemCount(pageSize); CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); @@ -253,6 +253,8 @@ public void queryScopedToSinglePartition_StartWithContinuationToken() throws Exc subscriber.assertComplete(); subscriber.assertNoErrors(); assertThat(subscriber.valueCount()).isEqualTo(1); + + @SuppressWarnings("unchecked") FeedResponse page = (FeedResponse) subscriber.getEvents().get(0).get(0); assertThat(page.getResults()).hasSize(3); @@ -444,7 +446,7 @@ private void assertInvalidContinuationToken(String query, int[] pageSize, List queryWithContinuationTokens(String query, int do { FeedOptions options = new FeedOptions(); options.setMaxItemCount(pageSize); - + options.setMaxDegreeOfParallelism(2); options.setRequestContinuation(requestContinuation); CosmosPagedFlux queryObservable = createdCollection.queryItems(query, @@ -497,6 +499,7 @@ private List queryWithContinuationTokens(String query, int testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); + @SuppressWarnings("unchecked") FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getContinuationToken(); receivedDocuments.addAll(firstPage.getResults()); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/ParallelDocumentQueryTest.java index ec96eedc12ff..f60cc96a4201 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/ParallelDocumentQueryTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/ParallelDocumentQueryTest.java @@ -300,6 +300,7 @@ public void queryDocumentsStringValue(){ } @Test(groups = { "simple" }) + @SuppressWarnings("rawtypes") public void queryDocumentsArrayValue(){ FeedOptions options = new FeedOptions(); @@ -539,6 +540,7 @@ private List queryWithContinuationTokens(String query, int testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); + @SuppressWarnings("unchecked") FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getContinuationToken(); receivedDocuments.addAll(firstPage.getResults()); diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/ResourceTokenTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/ResourceTokenTest.java index 8b86e2c19dff..af82066932fb 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/ResourceTokenTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/ResourceTokenTest.java @@ -272,7 +272,7 @@ public void readDocumentFromPermissionFeed(String documentUrl, Permission permis .withConsistencyLevel(ConsistencyLevel.SESSION).build(); RequestOptions options = new RequestOptions(); if (StringUtils.isNotEmpty(partitionKey)) { - options.setPartitionKey(new PartitionKey((String)partitionKey)); + options.setPartitionKey(new PartitionKey(partitionKey)); } else { options.setPartitionKey(PartitionKey.NONE); } diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/SinglePartitionDocumentQueryTest.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/SinglePartitionDocumentQueryTest.java index 423b25a4f487..655e31f5927a 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/SinglePartitionDocumentQueryTest.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/SinglePartitionDocumentQueryTest.java @@ -57,7 +57,7 @@ public void queryDocuments(boolean queryMetricsEnabled) throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - + options.setPopulateQueryMetrics(queryMetricsEnabled); CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); @@ -86,7 +86,7 @@ public void queryDocuments_ParameterizedQueryWithInClause() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - + CosmosPagedFlux queryObservable = createdCollection.queryItems(sqs, options, CosmosItemProperties.class); List expectedDocs = createdDocuments.stream().filter(d -> (3 == d.getInt("prop") || 4 == d.getInt("prop"))).collect(Collectors.toList()); @@ -113,7 +113,7 @@ public void queryDocuments_ParameterizedQuery() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - + CosmosPagedFlux queryObservable = createdCollection.queryItems(sqs, options, CosmosItemProperties.class); List expectedDocs = createdDocuments.stream().filter(d -> 3 == d.getInt("prop")).collect(Collectors.toList()); @@ -137,7 +137,7 @@ public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - + CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() @@ -155,7 +155,7 @@ public void queryDocumentsWithPageSize() throws Exception { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); options.setMaxItemCount(3); - + CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); List expectedDocs = createdDocuments; @@ -180,7 +180,7 @@ public void queryOrderBy() throws Exception { String query = "SELECT * FROM r ORDER BY r.prop ASC"; FeedOptions options = new FeedOptions(); - + options.setMaxItemCount(3); CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); @@ -203,10 +203,10 @@ public void queryOrderBy() throws Exception { public void continuationToken() throws Exception { String query = "SELECT * FROM r ORDER BY r.prop ASC"; FeedOptions options = new FeedOptions(); - + options.setMaxItemCount(3); CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); - + TestSubscriber> subscriber = new TestSubscriber<>(); queryObservable.byPage().take(1).subscribe(subscriber); @@ -214,6 +214,7 @@ public void continuationToken() throws Exception { subscriber.assertComplete(); subscriber.assertNoErrors(); assertThat(subscriber.valueCount()).isEqualTo(1); + @SuppressWarnings("unchecked") FeedResponse page = ((FeedResponse) subscriber.getEvents().get(0).get(0)); assertThat(page.getResults()).hasSize(3); @@ -243,7 +244,7 @@ public void continuationToken() throws Exception { public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); - + CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); FailureValidator validator = new FailureValidator.Builder() diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TestSuiteBase.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TestSuiteBase.java index 83c5f9672658..4cb5138c09b3 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TestSuiteBase.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TestSuiteBase.java @@ -311,6 +311,7 @@ protected static void truncateCollection(CosmosAsyncContainer cosmosContainer) { logger.info("Finished truncating collection {}.", cosmosContainerId); } + @SuppressWarnings({"fallthrough"}) protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (clientBuilder.getConsistencyLevel()) { case EVENTUAL: @@ -466,7 +467,7 @@ public static CosmosItemProperties createDocument(CosmosAsyncContainer cosmosCon return BridgeInternal.getProperties(cosmosContainer.createItem(item).block()); } - public Flux bulkInsert(CosmosAsyncContainer cosmosContainer, + public Flux> bulkInsert(CosmosAsyncContainer cosmosContainer, List documentDefinitionList, int concurrencyLevel) { List>> result = @@ -481,7 +482,7 @@ public List bulkInsertBlocking(CosmosAsyncContainer cosmos List documentDefinitionList) { return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .publishOn(Schedulers.parallel()) - .map(itemResponse -> (CosmosItemProperties)itemResponse.getItem()) + .map(itemResponse -> itemResponse.getItem()) .collectList() .block(); } @@ -737,14 +738,17 @@ static protected void safeCloseSyncClient(CosmosClient client) { } } + @SuppressWarnings("rawtypes") public void validateSuccess(Mono single, CosmosResponseValidator validator) { validateSuccess(single, validator, subscriberValidationTimeout); } + @SuppressWarnings("rawtypes") public void validateSuccess(Mono single, CosmosResponseValidator validator, long timeout) { validateSuccess(single.flux(), validator, timeout); } + @SuppressWarnings("rawtypes") public static void validateSuccess(Flux flowable, CosmosResponseValidator validator, long timeout) { @@ -758,11 +762,13 @@ public static void validateSuccess(Flux flowable, validator.validate(testSubscriber.values().get(0)); } + @SuppressWarnings("rawtypes") public void validateFailure(Mono mono, FailureValidator validator) throws InterruptedException { validateFailure(mono.flux(), validator, subscriberValidationTimeout); } + @SuppressWarnings("rawtypes") public static void validateFailure(Flux flowable, FailureValidator validator, long timeout) throws InterruptedException { @@ -776,6 +782,7 @@ public static void validateFailur validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } + @SuppressWarnings("rawtypes") public void validateItemSuccess( Mono responseMono, CosmosItemResponseValidator validator) { @@ -788,6 +795,7 @@ public void validateItemSuccess( validator.validate(testSubscriber.values().get(0)); } + @SuppressWarnings("rawtypes") public void validateItemFailure( Mono responseMono, FailureValidator validator) { TestSubscriber testSubscriber = new TestSubscriber<>(); @@ -973,6 +981,7 @@ static List parseDesiredConsistencies(String consistencies) { } } + @SuppressWarnings("fallthrough") static List allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List testConsistencies = new ArrayList<>(); switch (accountConsistency) { diff --git a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TopQueryTests.java b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TopQueryTests.java index 564924080212..0dd4d8d286dc 100644 --- a/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TopQueryTests.java +++ b/sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TopQueryTests.java @@ -49,7 +49,7 @@ public TopQueryTests(CosmosClientBuilder clientBuilder) { public void queryDocumentsWithTop(boolean qmEnabled) throws Exception { FeedOptions options = new FeedOptions(); - + options.setMaxItemCount(9); options.setMaxDegreeOfParallelism(2); options.setPopulateQueryMetrics(qmEnabled); @@ -145,10 +145,10 @@ private List queryWithContinuationTokens(String query, int do { FeedOptions options = new FeedOptions(); options.setMaxItemCount(pageSize); - + options.setMaxDegreeOfParallelism(2); options.setRequestContinuation(requestContinuation); - CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); + CosmosPagedFlux queryObservable = createdCollection.queryItems(query, options, CosmosItemProperties.class); //Observable> firstPageObservable = queryObservable.first(); TestSubscriber> testSubscriber = new TestSubscriber<>(); @@ -157,6 +157,7 @@ private List queryWithContinuationTokens(String query, int testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); + @SuppressWarnings("unchecked") FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getContinuationToken(); receivedDocuments.addAll(firstPage.getResults());