comment
stringlengths
1
45k
method_body
stringlengths
23
281k
target_code
stringlengths
0
5.16k
method_body_after
stringlengths
12
281k
context_before
stringlengths
8
543k
context_after
stringlengths
8
543k
This field is optional. The value of token here is `enabled`. This resulted line 202 skipping the `enabled` and getting the `VALUE_TRUE`/`VALUE_FALSE`, so it is never set.
public static SecretReferenceConfigurationSetting parseSecretReferenceFieldValue(String key, String value) { try { JsonParser parser = FACTORY.createParser(value.getBytes(StandardCharsets.UTF_8)); parser.nextToken(); JsonToken token = parser.nextToken(); String secretId = null; if (token == JsonToken.FIELD_NAME && URI.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { secretId = parser.getText(); } } SecretReferenceConfigurationSetting secretReferenceConfigurationSetting = new SecretReferenceConfigurationSetting(key, secretId); parser.close(); return secretReferenceConfigurationSetting; } catch (IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } private static FeatureFlagConfigurationSetting getFeatureFlagPropertyValue(JsonParser parser) throws IOException { JsonToken token = parser.nextToken(); token = parser.nextToken(); Map<String, Object> map = new HashMap<>(); if (token == JsonToken.FIELD_NAME && ID.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { map.put(ID, parser.getText()); } token = parser.nextToken(); } if (token == JsonToken.FIELD_NAME && DESCRIPTION.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { map.put(DESCRIPTION, parser.getText()); } token = parser.nextToken(); } if (token == JsonToken.FIELD_NAME && DISPLAY_NAME.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { map.put(DISPLAY_NAME, parser.getText()); } token = parser.nextToken(); } if (token == JsonToken.FIELD_NAME && ENABLED.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE) { map.put(ENABLED, parser.getBooleanValue()); } token = parser.nextToken(); } FeatureFlagConfigurationSetting featureFlagConfigurationSetting = new FeatureFlagConfigurationSetting((String) map.get(ID), (boolean) map.get(ENABLED)) .setDisplayName((String) map.get(DISPLAY_NAME)) .setDescription((String) map.get(DESCRIPTION)); if (token == JsonToken.FIELD_NAME && CONDITIONS.equals(parser.getCurrentName())) { parser.nextToken(); token = parser.nextToken(); if (token == JsonToken.FIELD_NAME && CLIENT_FILTERS.equals(parser.getCurrentName())) { featureFlagConfigurationSetting.setClientFilters(readClientFilters(parser)); } } parser.close(); return featureFlagConfigurationSetting; } @SuppressWarnings("unchecked") private static List<FeatureFlagFilter> readClientFilters(JsonParser parser) throws IOException { List<FeatureFlagFilter> filters = new ArrayList<>(); JsonToken token = parser.nextToken(); while (token != END_ARRAY) { FeatureFlagFilter flagFilter = null; if (token == JsonToken.FIELD_NAME && NAME.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { flagFilter = new FeatureFlagFilter(parser.getText()); } } token = parser.nextToken(); if (token == JsonToken.FIELD_NAME && PARAMETERS.equals(parser.getCurrentName())) { final Object propertyValue = readAdditionalPropertyValue(parser); if (!(propertyValue instanceof Map)) { throw LOGGER.logExceptionAsError(new IllegalStateException( "property class type should be Map<String, Object>, it represents a json data format in Java.") ); } flagFilter.setParameters((Map<String, Object>) propertyValue); filters.add(flagFilter); } } return filters; } private static Object readAdditionalPropertyValue(JsonParser parser) throws IOException { JsonToken token = parser.nextToken(); switch (token) { case END_OBJECT: case START_OBJECT: case END_ARRAY: return readAdditionalPropertyValue(parser); case START_ARRAY: parser.nextToken(); return readAdditionalPropertyValue(parser); case FIELD_NAME: final String currentName = parser.getCurrentName(); Map<String, Object> kv = new HashMap<>(); kv.put(currentName, readAdditionalPropertyValue(parser)); return kv; case VALUE_STRING: return parser.getText(); case VALUE_NUMBER_INT: return parser.getIntValue(); case VALUE_NUMBER_FLOAT: return parser.getFloatValue(); case VALUE_FALSE: case VALUE_TRUE: return parser.getBooleanValue(); default: case VALUE_NULL: return null; } } }
if (token == JsonToken.FIELD_NAME && DISPLAY_NAME.equals(parser.getCurrentName())) {
public static SecretReferenceConfigurationSetting parseSecretReferenceFieldValue(String key, String value) { try { JsonParser parser = FACTORY.createParser(value.getBytes(StandardCharsets.UTF_8)); parser.nextToken(); JsonToken token = parser.nextToken(); String secretId = null; if (token == JsonToken.FIELD_NAME && URI.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { secretId = parser.getText(); } } SecretReferenceConfigurationSetting secretReferenceConfigurationSetting = new SecretReferenceConfigurationSetting(key, secretId); parser.close(); return secretReferenceConfigurationSetting; } catch (IOException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } private static FeatureFlagConfigurationSetting getFeatureFlagPropertyValue(JsonParser parser) throws IOException { JsonToken token = parser.nextToken(); token = parser.nextToken(); Map<String, Object> map = new HashMap<>(); if (token == JsonToken.FIELD_NAME && ID.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { map.put(ID, parser.getText()); } token = parser.nextToken(); } if (token == JsonToken.FIELD_NAME && DESCRIPTION.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { map.put(DESCRIPTION, parser.getText()); } token = parser.nextToken(); } if (token == JsonToken.FIELD_NAME && DISPLAY_NAME.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { map.put(DISPLAY_NAME, parser.getText()); } token = parser.nextToken(); } if (token == JsonToken.FIELD_NAME && ENABLED.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE) { map.put(ENABLED, parser.getBooleanValue()); } token = parser.nextToken(); } FeatureFlagConfigurationSetting featureFlagConfigurationSetting = new FeatureFlagConfigurationSetting((String) map.get(ID), (boolean) map.get(ENABLED)) .setDisplayName((String) map.get(DISPLAY_NAME)) .setDescription((String) map.get(DESCRIPTION)); if (token == JsonToken.FIELD_NAME && CONDITIONS.equals(parser.getCurrentName())) { parser.nextToken(); token = parser.nextToken(); if (token == JsonToken.FIELD_NAME && CLIENT_FILTERS.equals(parser.getCurrentName())) { featureFlagConfigurationSetting.setClientFilters(readClientFilters(parser)); } } parser.close(); return featureFlagConfigurationSetting; } @SuppressWarnings("unchecked") private static List<FeatureFlagFilter> readClientFilters(JsonParser parser) throws IOException { List<FeatureFlagFilter> filters = new ArrayList<>(); JsonToken token = parser.nextToken(); while (token != END_ARRAY) { FeatureFlagFilter flagFilter = null; if (token == JsonToken.FIELD_NAME && NAME.equals(parser.getCurrentName())) { token = parser.nextToken(); if (token == JsonToken.VALUE_STRING) { flagFilter = new FeatureFlagFilter(parser.getText()); } } token = parser.nextToken(); if (token == JsonToken.FIELD_NAME && PARAMETERS.equals(parser.getCurrentName())) { final Object propertyValue = readAdditionalPropertyValue(parser); if (!(propertyValue instanceof Map)) { throw LOGGER.logExceptionAsError(new IllegalStateException( "property class type should be Map<String, Object>, it represents a json data format in Java.") ); } flagFilter.setParameters((Map<String, Object>) propertyValue); filters.add(flagFilter); } } return filters; } private static Object readAdditionalPropertyValue(JsonParser parser) throws IOException { JsonToken token = parser.nextToken(); switch (token) { case END_OBJECT: case START_OBJECT: case END_ARRAY: return readAdditionalPropertyValue(parser); case START_ARRAY: parser.nextToken(); return readAdditionalPropertyValue(parser); case FIELD_NAME: final String currentName = parser.getCurrentName(); Map<String, Object> kv = new HashMap<>(); kv.put(currentName, readAdditionalPropertyValue(parser)); return kv; case VALUE_STRING: return parser.getText(); case VALUE_NUMBER_INT: return parser.getIntValue(); case VALUE_NUMBER_FLOAT: return parser.getFloatValue(); case VALUE_FALSE: case VALUE_TRUE: return parser.getBooleanValue(); default: case VALUE_NULL: return null; } } }
class KeyValue to public-explored ConfigurationSetting. */ public static ConfigurationSetting toConfigurationSetting(KeyValue keyValue) { if (keyValue == null) { return null; } final String contentType = keyValue.getContentType(); final String key = keyValue.getKey(); final String value = keyValue.getValue(); final String label = keyValue.getLabel(); final String etag = keyValue.getEtag(); final Map<String, String> tags = keyValue.getTags(); final ConfigurationSetting setting = new ConfigurationSetting() .setKey(key) .setValue(value) .setLabel(label) .setContentType(contentType) .setETag(etag) .setTags(tags); ConfigurationSettingHelper.setLastModified(setting, keyValue.getLastModified()); ConfigurationSettingHelper.setReadOnly(setting, keyValue.isLocked() == null ? false : keyValue.isLocked()); try { if (FEATURE_FLAG_CONTENT_TYPE.equals(contentType)) { return subclassConfigurationSettingReflection(setting, parseFeatureFlagValue(setting.getValue())) .setKey(setting.getKey()) .setValue(setting.getValue()) .setLabel(setting.getLabel()) .setETag(setting.getETag()) .setContentType(setting.getContentType()) .setTags(setting.getTags()); } else if (SECRET_REFERENCE_CONTENT_TYPE.equals(contentType)) { return subclassConfigurationSettingReflection(setting, parseSecretReferenceFieldValue(setting.getKey(), setting.getValue())) .setValue(value) .setLabel(label) .setETag(etag) .setContentType(contentType) .setTags(tags); } else { return setting; } } catch (Exception exception) { throw LOGGER.logExceptionAsError(new RuntimeException( "The setting is neither a 'FeatureFlagConfigurationSetting' nor " + "'SecretReferenceConfigurationSetting', return the setting as 'ConfigurationSetting'. " + "Error: ", exception)); } }
class KeyValue to public-explored ConfigurationSetting. */ public static ConfigurationSetting toConfigurationSetting(KeyValue keyValue) { if (keyValue == null) { return null; } final String contentType = keyValue.getContentType(); final String key = keyValue.getKey(); final String value = keyValue.getValue(); final String label = keyValue.getLabel(); final String etag = keyValue.getEtag(); final Map<String, String> tags = keyValue.getTags(); final ConfigurationSetting setting = new ConfigurationSetting() .setKey(key) .setValue(value) .setLabel(label) .setContentType(contentType) .setETag(etag) .setTags(tags); ConfigurationSettingHelper.setLastModified(setting, keyValue.getLastModified()); ConfigurationSettingHelper.setReadOnly(setting, keyValue.isLocked() == null ? false : keyValue.isLocked()); try { if (FEATURE_FLAG_CONTENT_TYPE.equals(contentType)) { return subclassConfigurationSettingReflection(setting, parseFeatureFlagValue(setting.getValue())) .setKey(setting.getKey()) .setValue(setting.getValue()) .setLabel(setting.getLabel()) .setETag(setting.getETag()) .setContentType(setting.getContentType()) .setTags(setting.getTags()); } else if (SECRET_REFERENCE_CONTENT_TYPE.equals(contentType)) { return subclassConfigurationSettingReflection(setting, parseSecretReferenceFieldValue(setting.getKey(), setting.getValue())) .setValue(value) .setLabel(label) .setETag(etag) .setContentType(contentType) .setTags(tags); } else { return setting; } } catch (Exception exception) { throw LOGGER.logExceptionAsError(new RuntimeException( "The setting is neither a 'FeatureFlagConfigurationSetting' nor " + "'SecretReferenceConfigurationSetting', return the setting as 'ConfigurationSetting'. " + "Error: ", exception)); } }
should this be Server_Generated_410?
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, HttpConstants.SubStatusCodes.UNKNOWN); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, HttpConstants.SubStatusCodes.UNKNOWN); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, HttpConstants.SubStatusCodes.UNKNOWN); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
HttpConstants.SubStatusCodes.UNKNOWN);
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, HttpConstants.SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
should this be server_service_unavailable or similar?
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, HttpConstants.SubStatusCodes.UNKNOWN); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, HttpConstants.SubStatusCodes.UNKNOWN); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, HttpConstants.SubStatusCodes.UNKNOWN); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
HttpConstants.SubStatusCodes.UNKNOWN);
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, HttpConstants.SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
use SERVER_GENERATED_408
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.UNKNOWN); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
SubStatusCodes.UNKNOWN);
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
use TRANSPORT_GENERATED_410
public boolean expire() { final CosmosException error; if ((this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) || this.args.serviceRequest().getNonIdempotentWriteRetriesEnabled()){ error = new GoneException(this.toString(), null, this.args.physicalAddressUri().getURI(), HttpConstants.SubStatusCodes.UNKNOWN); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddressUri().getURI()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); if (this.timestamps != null) { this.timestamps.transitTimeout(this.args.serviceRequest().isReadOnly(), this.args.timeCreated()); } return this.completeExceptionally(error); }
error = new GoneException(this.toString(), null, this.args.physicalAddressUri().getURI(), HttpConstants.SubStatusCodes.UNKNOWN);
public boolean expire() { final CosmosException error; if ((this.args.serviceRequest().isReadOnly() || !this.hasSendingRequestStarted()) || this.args.serviceRequest().getNonIdempotentWriteRetriesEnabled()){ error = new GoneException(this.toString(), null, this.args.physicalAddressUri().getURI(), HttpConstants.SubStatusCodes.TRANSPORT_GENERATED_410); } else { error = new RequestTimeoutException(this.toString(), this.args.physicalAddressUri().getURI()); } BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); if (this.timestamps != null) { this.timestamps.transitTimeout(this.args.serviceRequest().isReadOnly(), this.args.timeCreated()); } return this.completeExceptionally(error); }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> implements IRequestRecord { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile RntbdChannelStatistics channelStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeDecodeStarted; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; private volatile RntbdChannelAcquisitionTimeline channelAcquisitionTimeline; private volatile RntbdClientChannelHealthChecker.Timestamps timestamps; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } @Override public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { return this.stage(value, Instant.now()); } public RntbdRequestRecord stage(final Stage value, Instant time) { STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; this.channelAcquisitionTimeline = new RntbdChannelAcquisitionTimeline(); break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case DECODE_STARTED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to DECODE_STARTED, not {} to DECODE_STARTED", current); break; } this.timeDecodeStarted = time; break; case RECEIVED: if (current != Stage.DECODE_STARTED) { logger.debug("Expected transition from DECODE_STARTED to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timeDecodeStarted() { return this.timeDecodeStarted; } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public void channelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); if (requestManager != null) { this.channelStatistics = requestManager.getChannelStatistics(channel, channelAcquisitionTimeline); } } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public RntbdChannelStatistics channelStatistics() { return this.channelStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } @Override public RntbdChannelAcquisitionTimeline getChannelAcquisitionTimeline() { return this.channelAcquisitionTimeline; } @Override public long getRequestId() { return this.args.transportRequestId(); } public void setTimestamps(RntbdClientChannelHealthChecker.Timestamps timestamps) { this.timestamps = timestamps; } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeDecodeStarted = this.timeDecodeStarted(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeDecodeStarted == null ? timeCompletedOrNow : timeDecodeStarted), new RequestTimeline.Event("decodeTime", timeDecodeStarted, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public void stop() { this.args.stop(); } public void stop(Timer requests, Timer responses) { this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, DECODE_STARTED, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> implements IRequestRecord { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile RntbdChannelStatistics channelStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeChannelAcquisitionStarted; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeDecodeStarted; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; private volatile RntbdChannelAcquisitionTimeline channelAcquisitionTimeline; private volatile RntbdClientChannelHealthChecker.Timestamps timestamps; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } @Override public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { return this.stage(value, Instant.now()); } public RntbdRequestRecord stage(final Stage value, Instant time) { STAGE.updateAndGet(this, current -> { switch (value) { case CHANNEL_ACQUISITION_STARTED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to CHANNEL_ACQUISITION_STARTED, not {} to CHANNEL_ACQUISITION_STARTED", current); break; } this.timeChannelAcquisitionStarted = time; this.channelAcquisitionTimeline = new RntbdChannelAcquisitionTimeline(); break; case PIPELINED: if (current != Stage.CHANNEL_ACQUISITION_STARTED) { logger.debug("Expected transition from CHANNEL_ACQUISITION_STARTED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case DECODE_STARTED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to DECODE_STARTED, not {} to DECODE_STARTED", current); break; } this.timeDecodeStarted = time; break; case RECEIVED: if (current != Stage.DECODE_STARTED) { logger.debug("Expected transition from DECODE_STARTED to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeChannelAcquisitionStarted() { return this.timeChannelAcquisitionStarted; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timeDecodeStarted() { return this.timeDecodeStarted; } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public void channelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); if (requestManager != null) { this.channelStatistics = requestManager.getChannelStatistics(channel, channelAcquisitionTimeline); } } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public RntbdChannelStatistics channelStatistics() { return this.channelStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } @Override public RntbdChannelAcquisitionTimeline getChannelAcquisitionTimeline() { return this.channelAcquisitionTimeline; } @Override public long getRequestId() { return this.args.transportRequestId(); } public void setTimestamps(RntbdClientChannelHealthChecker.Timestamps timestamps) { this.timestamps = timestamps; } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timeChannelAcquisitionStarted = this.timeChannelAcquisitionStarted(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeDecodeStarted = this.timeDecodeStarted(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timeChannelAcquisitionStarted == null ? timeCompletedOrNow : timeChannelAcquisitionStarted), new RequestTimeline.Event("channelAcquisitionStarted", timeChannelAcquisitionStarted, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeDecodeStarted == null ? timeCompletedOrNow : timeDecodeStarted), new RequestTimeline.Event("decodeTime", timeDecodeStarted, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public void stop() { this.args.stop(); } public void stop(Timer requests, Timer responses) { this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, CHANNEL_ACQUISITION_STARTED, PIPELINED, SENT, DECODE_STARTED, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
updated.
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, HttpConstants.SubStatusCodes.UNKNOWN); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, HttpConstants.SubStatusCodes.UNKNOWN); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, HttpConstants.SubStatusCodes.UNKNOWN); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
HttpConstants.SubStatusCodes.UNKNOWN);
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, HttpConstants.SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
Updated
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, HttpConstants.SubStatusCodes.UNKNOWN); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, HttpConstants.SubStatusCodes.UNKNOWN); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, HttpConstants.SubStatusCodes.UNKNOWN); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
HttpConstants.SubStatusCodes.UNKNOWN);
private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { final Long transportRequestId = response.getTransportRequestId(); if (transportRequestId == null) { reportIssue(context, "response ignored because its transportRequestId is missing: {}", response); return; } final RntbdRequestRecord requestRecord = this.pendingRequests.get(transportRequestId); if (requestRecord == null) { logger.debug("response {} ignored because its requestRecord is missing: {}", transportRequestId, response); return; } requestRecord.stage(RntbdRequestRecord.Stage.DECODE_STARTED, response.getDecodeStartTime()); requestRecord.stage( RntbdRequestRecord.Stage.RECEIVED, response.getDecodeEndTime() != null ? response.getDecodeEndTime() : Instant.now()); requestRecord.responseLength(response.getMessageLength()); final HttpResponseStatus status = response.getStatus(); final UUID activityId = response.getActivityId(); final int statusCode = status.code(); if ((HttpResponseStatus.OK.code() <= statusCode && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) || statusCode == HttpResponseStatus.NOT_MODIFIED.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeWithInjectedDelay(context, requestRecord, storeResponse, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.complete(storeResponse); } else { final CosmosException cause; final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); final CosmosError error = response.hasPayload() ? new CosmosError(RntbdObjectMapper.readTree(response)) : new CosmosError(Integer.toString(statusCode), status.reasonPhrase(), status.codeClass().name()); final Map<String, String> responseHeaders = response.getHeaders().asMap( this.rntbdContext().orElseThrow(IllegalStateException::new), activityId ); final String resourceAddress = requestRecord.args().physicalAddressUri() != null ? requestRecord.args().physicalAddressUri().getURI().toString() : null; switch (status.code()) { case StatusCodes.BADREQUEST: cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT_OR_MERGE: cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: GoneException goneExceptionFromService = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_410); goneExceptionFromService.setIsBasedOn410ResponseFromService(); cause = goneExceptionFromService; break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: Exception inner = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); cause = new GoneException(resourceAddress, error, lsn, partitionKeyRangeId, responseHeaders, inner, SubStatusCodes.SERVER_GENERATED_408); break; case StatusCodes.RETRY_WITH: cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders, SubStatusCodes.SERVER_GENERATED_503); break; case StatusCodes.TOO_MANY_REQUESTS: cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); break; default: cause = BridgeInternal.createCosmosException(resourceAddress, status.code(), error, responseHeaders); break; } BridgeInternal.setResourceAddress(cause, resourceAddress); if (this.serverErrorInjector != null) { Consumer<Duration> completeWithInjectedDelayConsumer = (delay) -> this.completeExceptionallyWithInjectedDelay(context, requestRecord, cause, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayAfterProcessing( requestRecord, completeWithInjectedDelayConsumer)) { return; } } requestRecord.completeExceptionally(cause); } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, HttpConstants.SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
class RntbdRequestManager implements ChannelHandler, ChannelInboundHandler, ChannelOutboundHandler { private static final ClosedChannelException ON_CHANNEL_UNREGISTERED = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "channelUnregistered"); private static final ClosedChannelException ON_CLOSE = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "close"); private static final ClosedChannelException ON_DEREGISTER = ThrowableUtil.unknownStackTrace(new ClosedChannelException(), RntbdRequestManager.class, "deregister"); private static final String FAULT_INJECTION_RULE_ID_KEY_NAME = "faultInjectionRuleId"; private static final AttributeKey<String> FAULT_INJECTION_RULE_ID_KEY = AttributeKey.newInstance( FAULT_INJECTION_RULE_ID_KEY_NAME); private static final EventExecutor requestExpirationExecutor = new DefaultEventExecutor(new RntbdThreadFactory( "request-expirator", true, Thread.NORM_PRIORITY)); private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); private final CompletableFuture<RntbdContext> contextFuture = new CompletableFuture<>(); private final CompletableFuture<RntbdContextRequest> contextRequestFuture = new CompletableFuture<>(); private final ChannelHealthChecker healthChecker; private final int pendingRequestLimit; private final ConcurrentHashMap<Long, RntbdRequestRecord> pendingRequests; private final Timestamps timestamps = new Timestamps(); private final RntbdConnectionStateListener rntbdConnectionStateListener; private final long idleConnectionTimerResolutionInNanos; private final long tcpNetworkRequestTimeoutInNanos; private final RntbdServerErrorInjector serverErrorInjector; private boolean closingExceptionally = false; private CoalescingBufferQueue pendingWrites; public RntbdRequestManager( final ChannelHealthChecker healthChecker, final int pendingRequestLimit, final RntbdConnectionStateListener connectionStateListener, final long idleConnectionTimerResolutionInNanos, final RntbdServerErrorInjector serverErrorInjector, final long tcpNetworkRequestTimeoutInNanos) { checkArgument(pendingRequestLimit > 0, "pendingRequestLimit: %s", pendingRequestLimit); checkNotNull(healthChecker, "healthChecker"); this.pendingRequests = new ConcurrentHashMap<>(pendingRequestLimit); this.pendingRequestLimit = pendingRequestLimit; this.healthChecker = healthChecker; this.rntbdConnectionStateListener = connectionStateListener; this.idleConnectionTimerResolutionInNanos = idleConnectionTimerResolutionInNanos; this.tcpNetworkRequestTimeoutInNanos = tcpNetworkRequestTimeoutInNanos; this.serverErrorInjector = serverErrorInjector; } /** * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerAdded(final ChannelHandlerContext context) { this.traceOperation(context, "handlerAdded"); } /** * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events * anymore. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void handlerRemoved(final ChannelHandlerContext context) { this.traceOperation(context, "handlerRemoved"); } /** * The {@link Channel} of the {@link ChannelHandlerContext} is now active * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelActive(final ChannelHandlerContext context) { this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was registered and has reached the end of its lifetime * <p> * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelInactive(final ChannelHandlerContext context) { this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} has read a message from its peer. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs. * @param message The message read. */ @Override public void channelRead(final ChannelHandlerContext context, final Object message) { this.traceOperation(context, "channelRead"); this.timestamps.channelReadCompleted(); try { if (message.getClass() == RntbdResponse.class) { try { this.messageReceived(context, (RntbdResponse) message); } catch (CorruptedFrameException error) { this.exceptionCaught(context, error); } catch (Throwable throwable) { reportIssue(context, "{} ", message, throwable); this.exceptionCaught(context, throwable); } } else { final IllegalStateException error = new IllegalStateException( lenientFormat("expected message of %s, not %s: %s", RntbdResponse.class, message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } } finally { if (message instanceof ReferenceCounted) { boolean released = ((ReferenceCounted) message).release(); reportIssueUnless(released, context, "failed to release message: {}", message); } } } /** * The {@link Channel} of the {@link ChannelHandlerContext} has fully consumed the most-recent message read. * <p> * If {@link ChannelOption * {@link Channel} will be made until {@link ChannelHandlerContext * for outbound messages to be written. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelReadComplete(final ChannelHandlerContext context) { this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} * <p> * This method then calls {@link ChannelHandlerContext * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. * <p> * Sub-classes may override this method to change behavior. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override public void channelRegistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelRegistered"); reportIssueUnless(this.pendingWrites == null, context, "pendingWrites: {}", pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); context.fireChannelRegistered(); } /** * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelUnregistered(final ChannelHandlerContext context) { this.traceOperation(context, "channelUnregistered"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CHANNEL_UNREGISTERED); } else { logger.debug("{} channelUnregistered exceptionally", context); } context.fireChannelUnregistered(); } /** * Gets called once the writable state of a {@link Channel} changed. You can check the state with * {@link Channel * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } /** * Processes {@link ChannelHandlerContext * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param cause Exception caught */ @Override @SuppressWarnings("deprecation") public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { this.traceOperation(context, "exceptionCaught", cause); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, cause); if (logger.isDebugEnabled()) { logger.debug("{} closing due to:", context, cause); } context.flush().close(); } } /** * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline * <p> * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override public void userEventTriggered(final ChannelHandlerContext context, final Object event) { this.traceOperation(context, "userEventTriggered", event); try { if (event instanceof IdleStateEvent) { if (this.healthChecker instanceof RntbdClientChannelHealthChecker) { ((RntbdClientChannelHealthChecker) this.healthChecker) .isHealthyWithFailureReason(context.channel()).addListener((Future<String> future) -> { final Throwable cause; if (future.isSuccess()) { if (RntbdConstants.RntbdHealthCheckResults.SuccessValue.equals(future.get())) { return; } cause = new UnhealthyChannelException(future.get()); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } else { this.healthChecker.isHealthy(context.channel()).addListener((Future<Boolean> future) -> { final Throwable cause; if (future.isSuccess()) { if (future.get()) { return; } cause = new UnhealthyChannelException( MessageFormat.format( "Custom ChannelHealthChecker {0} failed.", this.healthChecker.getClass().getSimpleName())); } else { cause = future.cause(); } this.exceptionCaught(context, cause); }); } return; } if (event instanceof RntbdContext) { this.contextFuture.complete((RntbdContext) event); this.removeContextNegotiatorAndFlushPendingWrites(context); this.timestamps.channelReadCompleted(); return; } if (event instanceof RntbdContextException) { this.contextFuture.completeExceptionally((RntbdContextException) event); this.exceptionCaught(context, (RntbdContextException)event); return; } if (event instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent sslHandshakeCompletionEvent = (SslHandshakeCompletionEvent) event; if (sslHandshakeCompletionEvent.isSuccess()) { if (logger.isDebugEnabled()) { logger.debug("SslHandshake completed, adding idleStateHandler"); } context.pipeline().addAfter( SslHandler.class.toString(), IdleStateHandler.class.toString(), new IdleStateHandler( this.idleConnectionTimerResolutionInNanos, this.idleConnectionTimerResolutionInNanos, 0, TimeUnit.NANOSECONDS)); } else { if (logger.isDebugEnabled()) { logger.debug("SslHandshake failed", sslHandshakeCompletionEvent.cause()); } this.exceptionCaught(context, sslHandshakeCompletionEvent.cause()); return; } } if (event instanceof RntbdFaultInjectionConnectionResetEvent) { logger.warn( "Inject Connection reset with ruleId {} ", ((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionResetEvent) event).getFaultInjectionRuleId()); this.exceptionCaught(context, new IOException("Fault Injection Connection Reset")); return; } if (event instanceof RntbdFaultInjectionConnectionCloseEvent) { logger.warn( "Inject Connection close with ruleId {} ", ((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).set(((RntbdFaultInjectionConnectionCloseEvent) event).getFaultInjectionRuleId()); context.close(); return; } context.fireUserEventTriggered(event); } catch (Throwable error) { reportIssue(context, "{}: ", event, error); this.exceptionCaught(context, error); } } /** * Called once a bind operation is made. * * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** * Called once a close operation is made. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void close(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "close"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_CLOSE); } else { logger.debug("{} closed exceptionally", context); } final SslHandler sslHandler = context.pipeline().get(SslHandler.class); if (sslHandler != null) { try { sslHandler.closeOutbound(); } catch (Exception exception) { if (exception instanceof SSLException) { logger.debug( "SslException when attempting to close the outbound SSL connection: ", exception); } else { logger.warn( "Exception when attempting to close the outbound SSL connection: ", exception); throw exception; } } } context.close(promise); } /** * Called once a connect operation is made. * * @param context the {@link ChannelHandlerContext} for which the connect operation is made * @param remoteAddress the {@link SocketAddress} to which it should connect * @param localAddress the {@link SocketAddress} which is used as source on connect * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void connect( final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise ) { this.traceOperation(context, "connect", remoteAddress, localAddress); context.connect(remoteAddress, localAddress, promise); } /** * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the deregister operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "deregister"); if (!this.closingExceptionally) { this.completeAllPendingRequestsExceptionally(context, ON_DEREGISTER); } else { logger.debug("{} deregistered exceptionally", context); } context.deregister(promise); } /** * Called once a disconnect operation is made. * * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { this.traceOperation(context, "disconnect"); context.disconnect(promise); } /** * Called once a flush operation is made * <p> * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made */ @Override public void flush(final ChannelHandlerContext context) { this.traceOperation(context, "flush"); context.flush(); } /** * Intercepts {@link ChannelHandlerContext * * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override public void read(final ChannelHandlerContext context) { this.traceOperation(context, "read"); context.read(); } /** * Called once a write operation is made * <p> * The write operation will send messages through the {@link ChannelPipeline} which are then ready to be flushed * to the actual {@link Channel}. This will occur when {@link Channel * * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { this.traceOperation(context, "write", message); if (message instanceof RntbdRequestRecord) { final RntbdRequestRecord record = (RntbdRequestRecord) message; record.setTimestamps(this.timestamps); if (!record.isCancelled()) { record.setSendingRequestHasStarted(); this.timestamps.channelWriteAttempted(); if (this.serverErrorInjector != null) { if (this.serverErrorInjector.injectRntbdServerResponseError(record)) { this.timestamps.channelWriteCompleted(); this.timestamps.channelReadCompleted(); return; } Consumer<Duration> writeRequestWithInjectedDelayConsumer = (delay) -> this.writeRequestWithInjectedDelay(context, record, promise, delay); if (this.serverErrorInjector.injectRntbdServerResponseDelayBeforeProcessing( record, writeRequestWithInjectedDelayConsumer)) { return; } } context.write(this.addPendingRequestRecord(context, record), promise).addListener(completed -> { record.stage(RntbdRequestRecord.Stage.SENT); if (completed.isSuccess()) { this.timestamps.channelWriteCompleted(); } }); } return; } if (message == RntbdHealthCheckRequest.MESSAGE) { context.write(RntbdHealthCheckRequest.MESSAGE, promise).addListener(completed -> { if (completed.isSuccess()) { this.timestamps.channelPingCompleted(); } }); return; } final IllegalStateException error = new IllegalStateException(lenientFormat("message of %s: %s", message.getClass(), message)); reportIssue(context, "", error); this.exceptionCaught(context, error); } private void writeRequestWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final ChannelPromise promise, Duration delay) { this.addPendingRequestRecord(context, rntbdRequestRecord); rntbdRequestRecord.stage(RntbdRequestRecord.Stage.SENT); this.timestamps.channelWriteCompleted(); this.timestamps.channelWriteCompleted(); long effectiveDelayInNanos = Math.min(this.tcpNetworkRequestTimeoutInNanos, delay.toNanos()); context.executor().schedule( () -> { if (this.tcpNetworkRequestTimeoutInNanos <= delay.toNanos()) { return; } context.write(rntbdRequestRecord, promise); }, effectiveDelayInNanos, TimeUnit.NANOSECONDS ); } private void completeWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final StoreResponse storeResponse, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.complete(storeResponse); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } private void completeExceptionallyWithInjectedDelay( final ChannelHandlerContext context, final RntbdRequestRecord rntbdRequestRecord, final CosmosException cause, Duration delay) { long actualTransitTime = Duration.between(rntbdRequestRecord.timeCreated(), Instant.now()).toNanos(); if (actualTransitTime + delay.toNanos() > this.tcpNetworkRequestTimeoutInNanos) { return; } context.executor().schedule( () -> { rntbdRequestRecord.completeExceptionally(cause); }, delay.toNanos(), TimeUnit.NANOSECONDS ); } public RntbdChannelStatistics getChannelStatistics( Channel channel, RntbdChannelAcquisitionTimeline channelAcquisitionTimeline) { return new RntbdChannelStatistics() .channelId(channel.id().toString()) .pendingRequestsCount(this.pendingRequests.size()) .channelTaskQueueSize(RntbdUtils.tryGetExecutorTaskQueueSize(channel.eventLoop())) .lastReadTime(this.timestamps.lastChannelReadTime()) .transitTimeoutCount(this.timestamps.transitTimeoutCount()) .transitTimeoutStartingTime(this.timestamps.transitTimeoutStartingTime()) .waitForConnectionInit(channelAcquisitionTimeline.isWaitForChannelInit()); } int pendingRequestCount() { return this.pendingRequests.size(); } Optional<RntbdContext> rntbdContext() { return Optional.of(this.contextFuture.getNow(null)); } CompletableFuture<RntbdContextRequest> rntbdContextRequestFuture() { return this.contextRequestFuture; } boolean hasRequestedRntbdContext() { return this.contextRequestFuture.getNow(null) != null; } boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } RntbdChannelState getChannelState(final int demand) { reportIssueUnless(this.hasRequestedRntbdContext(), this, "Direct TCP context request was not issued"); final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); if (this.pendingRequests.size() < limit) { return RntbdChannelState.ok(this.pendingRequests.size()); } if (this.hasRntbdContext()) { return RntbdChannelState.pendingLimit(this.pendingRequests.size()); } else { return RntbdChannelState.contextNegotiationPending((this.pendingRequests.size())); } } void pendWrite(final ByteBuf out, final ChannelPromise promise) { this.pendingWrites.add(out, promise); } public Timestamps getTimestamps() { return this.timestamps; } Timestamps snapshotTimestamps() { return new Timestamps(this.timestamps); } private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { AtomicReference<Timeout> pendingRequestTimeout = new AtomicReference<>(); this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); pendingRequestTimeout.set(record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); })); return record; }); record.whenComplete((response, error) -> { this.pendingRequests.remove(record.transportRequestId()); if (pendingRequestTimeout.get() != null) { pendingRequestTimeout.get().cancel(); } }); return record; } private void completeAllPendingRequestsExceptionally( final ChannelHandlerContext context, final Throwable throwable) { reportIssueUnless(!this.closingExceptionally, context, "", throwable); this.closingExceptionally = true; if (this.pendingWrites != null && !this.pendingWrites.isEmpty()) { this.pendingWrites.releaseAndFailAll(context, throwable); } if (this.rntbdConnectionStateListener != null) { this.rntbdConnectionStateListener.onException(throwable); } if (this.pendingRequests.isEmpty()) { return; } if (!this.contextRequestFuture.isDone()) { this.contextRequestFuture.completeExceptionally(throwable); } if (!this.contextFuture.isDone()) { this.contextFuture.completeExceptionally(throwable); } final int count = this.pendingRequests.size(); Exception contextRequestException = null; String phrase = null; if (this.contextRequestFuture.isCompletedExceptionally()) { try { this.contextRequestFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request write cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request write failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request write failed"; contextRequestException = new ChannelException(error); } } else if (this.contextFuture.isCompletedExceptionally()) { try { this.contextFuture.get(); } catch (final CancellationException error) { phrase = "RNTBD context request read cancelled"; contextRequestException = error; } catch (final Exception error) { phrase = "RNTBD context request read failed"; contextRequestException = error; } catch (final Throwable error) { phrase = "RNTBD context request read failed"; contextRequestException = new ChannelException(error); } } else { phrase = "closed exceptionally"; } final String message = lenientFormat("%s %s with %s pending requests", context, phrase, count); final Exception cause; if (throwable instanceof ClosedChannelException) { cause = contextRequestException == null ? (ClosedChannelException) throwable : contextRequestException; } else { cause = throwable instanceof Exception ? (Exception) throwable : new ChannelException(throwable); } String faultInjectionRuleId = StringUtils.EMPTY; if (context.channel().hasAttr(FAULT_INJECTION_RULE_ID_KEY)) { faultInjectionRuleId = context.channel().attr(FAULT_INJECTION_RULE_ID_KEY).getAndSet(StringUtils.EMPTY); } for (RntbdRequestRecord record : this.pendingRequests.values()) { final Map<String, String> requestHeaders = record.args().serviceRequest().getHeaders(); final String requestUri = record.args().physicalAddressUri().getURI().toString(); final GoneException error = new GoneException(message, cause, null, requestUri, SubStatusCodes.UNKNOWN); BridgeInternal.setRequestHeaders(error, requestHeaders); if (StringUtils.isNotEmpty(faultInjectionRuleId)) { record .args() .serviceRequest() .faultInjectionRequestContext .applyFaultInjectionRule(record.transportRequestId(), faultInjectionRuleId); } record.completeExceptionally(error); } } /** * This method is called for each incoming message of type {@link RntbdResponse} to complete a request. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager request manager} belongs. * @param response the {@link RntbdResponse message} received. */ private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); negotiator.removeInboundHandler(); negotiator.removeOutboundHandler(); if (!this.pendingWrites.isEmpty()) { this.pendingWrites.writeAndRemoveAll(context); context.flush(); } } private static void reportIssue(final Object subject, final String format, final Object... args) { RntbdReporter.reportIssue(logger, subject, format, args); } private static void reportIssueUnless( final boolean predicate, final Object subject, final String format, final Object... args ) { RntbdReporter.reportIssueUnless(logger, predicate, subject, format, args); } private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { logger.trace("{}\n{}\n{}", operationName, context, args); } public final static class UnhealthyChannelException extends ChannelException { public UnhealthyChannelException(String reason) { super("health check failed, reason: " + reason); } @Override public Throwable fillInStackTrace() { return this; } } }
currently, we require customers to set a targetThroughput or targetThroughputThreshold, else an `IllegalArgumentException` will be thrown during the validation step. however for priority throttling, my current understanding is priority level is the only required parameter, so we should also modify the checking above
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { throw new IllegalArgumentException("Neither targetThroughput nor targetThroughputThreshold is defined."); } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
this.priorityLevel,
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null && this.priorityLevel == null) { throw new IllegalArgumentException("All targetThroughput, targetThroughputThreshold and priorityLevel cannot be null or empty."); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { this.targetThroughput = Integer.MAX_VALUE; } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
Yeah right. That's the reason we have exposed `ThroughputControlGroupConfig.priorityGroupConfig` which internally sets the throughput thresholds. If the customer uses the builder they'll still need to set the targetThroughput or targetThroughputThreshold. Open to changing it to the way you are suggesting. @FabianMeiswinkel your thoughts?
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { throw new IllegalArgumentException("Neither targetThroughput nor targetThroughputThreshold is defined."); } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
this.priorityLevel,
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null && this.priorityLevel == null) { throw new IllegalArgumentException("All targetThroughput, targetThroughputThreshold and priorityLevel cannot be null or empty."); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { this.targetThroughput = Integer.MAX_VALUE; } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
ah I see, sorry missed that we are setting the threshold, so please ignore the above statement
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { throw new IllegalArgumentException("Neither targetThroughput nor targetThroughputThreshold is defined."); } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
this.priorityLevel,
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null && this.priorityLevel == null) { throw new IllegalArgumentException("All targetThroughput, targetThroughputThreshold and priorityLevel cannot be null or empty."); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { this.targetThroughput = Integer.MAX_VALUE; } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
I would make the change to also allow setting null for the targetThroughput/Threshold as long as priority is et to Low - so either throughput, threshold or low priority are required. When only priority is specified we should internally disable local throttling (or set a threshold >> 1 to implicitly do so. That would need some testing - but shouldn't be complicated
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { throw new IllegalArgumentException("Neither targetThroughput nor targetThroughputThreshold is defined."); } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
this.priorityLevel,
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null && this.priorityLevel == null) { throw new IllegalArgumentException("All targetThroughput, targetThroughputThreshold and priorityLevel cannot be null or empty."); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { this.targetThroughput = Integer.MAX_VALUE; } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
I would like to see whether we can set it to a value >> 1 - why? In some scenarios backend actually allows for significantly more than 100% of the expected throughput - when no throughput control threshold is specified we should not limit at all on the clinet. So something like 100, 1000 or even int max value
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null && this.priorityLevel == null) { throw new IllegalArgumentException("All targetThroughput, targetThroughputThreshold and priorityLevel cannot be null or empty."); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { this.targetThroughputThreshold = 1.0; } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
this.targetThroughputThreshold = 1.0;
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null && this.priorityLevel == null) { throw new IllegalArgumentException("All targetThroughput, targetThroughputThreshold and priorityLevel cannot be null or empty."); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { this.targetThroughput = Integer.MAX_VALUE; } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
This is changed to int max on targetThroughput.
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null && this.priorityLevel == null) { throw new IllegalArgumentException("All targetThroughput, targetThroughputThreshold and priorityLevel cannot be null or empty."); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { this.targetThroughputThreshold = 1.0; } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
this.targetThroughputThreshold = 1.0;
public ThroughputControlGroupConfig build() { if (StringUtils.isEmpty(this.groupName)) { throw new IllegalArgumentException("Group name cannot be null nor empty"); } if (this.targetThroughput == null && this.targetThroughputThreshold == null && this.priorityLevel == null) { throw new IllegalArgumentException("All targetThroughput, targetThroughputThreshold and priorityLevel cannot be null or empty."); } if (this.targetThroughput == null && this.targetThroughputThreshold == null) { this.targetThroughput = Integer.MAX_VALUE; } return new ThroughputControlGroupConfig( this.groupName, this.targetThroughput, this.targetThroughputThreshold, this.priorityLevel, this.isDefault, this.continueOnInitError); }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
class ThroughputControlGroupConfigBuilder { private static final boolean DEFAULT_CONTINUE_ON_INIT_ERROR = false; private String groupName; private Integer targetThroughput; private Double targetThroughputThreshold; private boolean isDefault; private PriorityLevel priorityLevel; private boolean continueOnInitError = DEFAULT_CONTINUE_ON_INIT_ERROR; /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setGroupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group name. * * @param groupName The throughput control group name. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder groupName(String groupName) { checkArgument(StringUtils.isNotEmpty(groupName), "Group name cannot be null nor empty"); this.groupName = groupName; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput. * * The target throughput value should be greater than 0. * * @param targetThroughput The target throughput for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughput(int targetThroughput) { checkArgument(targetThroughput > 0, "Target throughput should be greater than 0"); this.targetThroughput = targetThroughput; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setTargetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group target throughput threshold. * * The target throughput threshold value should be between (0, 1]. * * @param targetThroughputThreshold The target throughput threshold for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder targetThroughputThreshold(double targetThroughputThreshold) { checkArgument(targetThroughputThreshold > 0 && targetThroughputThreshold <= 1, "Target throughput threshold should between (0, 1]"); this.targetThroughputThreshold = targetThroughputThreshold; return this; } /** * Set the throughput control group priority level. * The priority level is used to determine which requests will be throttled first when the total throughput of all control groups exceeds the max throughput. * * By Default PriorityLevel for each request is treated as High. It can be explicitly set to Low for some requests. * * Refer to https: * * @param priorityLevel The priority level for the control group. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder priorityLevel(PriorityLevel priorityLevel) { this.priorityLevel = priorityLevel; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ @Deprecated @Beta(value = Beta.SinceVersion.V4_13_0, warningText = Beta.PREVIEW_SUBJECT_TO_CHANGE_WARNING) public ThroughputControlGroupConfigBuilder setDefault(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether this throughput control group will be used by default. * If set to true, requests without explicit override of the throughput control group will be routed to this group. * * @param aDefault The flag to indicate whether the throughput control group will be used by default. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder defaultControlGroup(boolean aDefault) { this.isDefault = aDefault; return this; } /** * Set whether allow request to continue on original request flow if throughput control controller failed on initialization. * If set to true, requests will be able to fall back to original request flow if throughput control controller failed on initialization. * * @param continueOnInitError The flag to indicate whether request is allowed to fall back to original request flow. * @return The {@link ThroughputControlGroupConfigBuilder}. */ public ThroughputControlGroupConfigBuilder continueOnInitError(boolean continueOnInitError) { this.continueOnInitError = continueOnInitError; return this; } /** * Validate the throughput configuration and create a new throughput control group config item. * * @return A new {@link ThroughputControlGroupConfig}. */ }
Nice catch Anu!
public Reactor createReactor(String connectionId, int maxFrameSize) throws IOException { final GlobalIOHandler globalIOHandler = new GlobalIOHandler(connectionId); final ReactorHandler reactorHandler = new ReactorHandler(connectionId); synchronized (lock) { if (this.reactor != null) { return this.reactor; } if (maxFrameSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxFrameSize' must be a positive number.")); } final ReactorOptions reactorOptions = new ReactorOptions(); reactorOptions.setMaxFrameSize(maxFrameSize); reactorOptions.setEnableSaslByDefault(true); final Reactor reactor = Proton.reactor(reactorOptions, reactorHandler); reactor.setGlobalHandler(globalIOHandler); final Pipe ioSignal = Pipe.open(); final ReactorDispatcher dispatcher = new ReactorDispatcher(connectionId, reactor, ioSignal); this.reactor = reactor; this.reactorDispatcher = dispatcher; } return this.reactor; }
final GlobalIOHandler globalIOHandler = new GlobalIOHandler(connectionId);
public Reactor createReactor(String connectionId, int maxFrameSize) throws IOException { final GlobalIOHandler globalIOHandler = new GlobalIOHandler(connectionId); final ReactorHandler reactorHandler = new ReactorHandler(connectionId); synchronized (lock) { if (this.reactor != null) { return this.reactor; } if (maxFrameSize <= 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxFrameSize' must be a positive number.")); } final ReactorOptions reactorOptions = new ReactorOptions(); reactorOptions.setMaxFrameSize(maxFrameSize); reactorOptions.setEnableSaslByDefault(true); final Reactor reactor = Proton.reactor(reactorOptions, reactorHandler); reactor.setGlobalHandler(globalIOHandler); final Pipe ioSignal = Pipe.open(); final ReactorDispatcher dispatcher = new ReactorDispatcher(connectionId, reactor, ioSignal); this.reactor = reactor; this.reactorDispatcher = dispatcher; } return this.reactor; }
class ReactorProvider { private static final ClientLogger LOGGER = new ClientLogger(ReactorProvider.class); private final Object lock = new Object(); private Reactor reactor; private ReactorDispatcher reactorDispatcher; public Reactor getReactor() { synchronized (lock) { return reactor; } } public ReactorDispatcher getReactorDispatcher() { synchronized (lock) { return reactorDispatcher; } } /** * Creates a reactor and replaces the existing instance of it. * * @param connectionId Identifier for Reactor. * @return The newly created reactor instance. * @throws IOException If the service could not create a Reactor instance. */ }
class ReactorProvider { private static final ClientLogger LOGGER = new ClientLogger(ReactorProvider.class); private final Object lock = new Object(); private Reactor reactor; private ReactorDispatcher reactorDispatcher; public Reactor getReactor() { synchronized (lock) { return reactor; } } public ReactorDispatcher getReactorDispatcher() { synchronized (lock) { return reactorDispatcher; } } /** * Creates a reactor and replaces the existing instance of it. * * @param connectionId Identifier for Reactor. * @return The newly created reactor instance. * @throws IOException If the service could not create a Reactor instance. */ }
Let's move this down into the else block below and make this calling more verbose. ```java if (isReactive) { // async call } else { if (syncDisabled) { // blocking async call } else { // full sync call } } ``` That way we only check the sync proxy enabled context when we actually have to instead of always checking it even when it won't be used (`methodParser.isReactive() == true`)
public Object invoke(Object proxy, final Method method, Object[] args) { RestProxyUtils.validateResumeOperationIsNotPresent(method); final SwaggerMethodParser methodParser = getMethodParser(method); RequestOptions options = methodParser.setRequestOptions(args); Context context = methodParser.setContext(args); boolean syncRestProxyEnabled = (boolean) context.getData(HTTP_REST_PROXY_SYNC_PROXY_ENABLED) .orElse(GLOBAL_SYNC_PROXY_ENABLED); if (methodParser.isReactive() || !syncRestProxyEnabled) { return asyncRestProxy.invoke(proxy, method, options, options != null ? options.getErrorOptions() : null, options != null ? options.getRequestCallback() : null, methodParser, methodParser.isReactive(), args); } else { return syncRestProxy.invoke(proxy, method, options, options != null ? options.getErrorOptions() : null, options != null ? options.getRequestCallback() : null, methodParser, false, args); } }
.orElse(GLOBAL_SYNC_PROXY_ENABLED);
public Object invoke(Object proxy, final Method method, Object[] args) { RestProxyUtils.validateResumeOperationIsNotPresent(method); final SwaggerMethodParser methodParser = getMethodParser(method); RequestOptions options = methodParser.setRequestOptions(args); Context context = methodParser.setContext(args); if (methodParser.isReactive() || isSyncDisabled(context)) { return asyncRestProxy.invoke(proxy, method, options, options != null ? options.getErrorOptions() : null, options != null ? options.getRequestCallback() : null, methodParser, methodParser.isReactive(), args); } else { return syncRestProxy.invoke(proxy, method, options, options != null ? options.getErrorOptions() : null, options != null ? options.getRequestCallback() : null, methodParser, false, args); } }
class RestProxy implements InvocationHandler { private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLED = "com.azure.core.http.restproxy.syncproxy.enable"; private static final boolean GLOBAL_SYNC_PROXY_ENABLED = Configuration.getGlobalConfiguration() .get("AZURE_HTTP_REST_PROXY_SYNC_PROXY_ENABLED", true); private final SwaggerInterfaceParser interfaceParser; private final AsyncRestProxy asyncRestProxy; private final HttpPipeline httpPipeline; private final SyncRestProxy syncRestProxy; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.interfaceParser = interfaceParser; this.asyncRestProxy = new AsyncRestProxy(httpPipeline, serializer, interfaceParser); this.syncRestProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); this.httpPipeline = httpPipeline; } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, RestProxyUtils.createDefaultPipeline(), RestProxyUtils.createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, RestProxyUtils.createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = SwaggerInterfaceParser.getInstance(swaggerInterface); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class RestProxy implements InvocationHandler { private static final String HTTP_REST_PROXY_SYNC_PROXY_ENABLED = "com.azure.core.http.restproxy.syncproxy.enable"; private static final boolean GLOBAL_SYNC_PROXY_ENABLED = Configuration.getGlobalConfiguration() .get("AZURE_HTTP_REST_PROXY_SYNC_PROXY_ENABLED", true); private final SwaggerInterfaceParser interfaceParser; private final AsyncRestProxy asyncRestProxy; private final HttpPipeline httpPipeline; private final SyncRestProxy syncRestProxy; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods that * this RestProxy "implements". */ private RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.interfaceParser = interfaceParser; this.asyncRestProxy = new AsyncRestProxy(httpPipeline, serializer, interfaceParser); this.syncRestProxy = new SyncRestProxy(httpPipeline, serializer, interfaceParser); this.httpPipeline = httpPipeline; } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger interface that this * RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser getMethodParser(Method method) { return interfaceParser.getMethodParser(method); } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override private static boolean isSyncDisabled(Context context) { return !(boolean) context .getData(HTTP_REST_PROXY_SYNC_PROXY_ENABLED) .orElse(GLOBAL_SYNC_PROXY_ENABLED); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, RestProxyUtils.createDefaultPipeline(), RestProxyUtils.createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, RestProxyUtils.createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http requests * @param serializer the serializer that will be used to convert POJOs to and from request and response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = SwaggerInterfaceParser.getInstance(swaggerInterface); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
Why is this API override logging?
public BinaryData getBodyAsBinaryData() { BinaryData content = actualResponse.getBodyAsBinaryData(); doLog(content.toString()); return content; }
doLog(content.toString());
public BinaryData getBodyAsBinaryData() { BinaryData content = actualResponse.getBodyAsBinaryData(); doLog(content.toString()); return content; }
class LoggingHttpResponse extends HttpResponse { private final HttpResponse actualResponse; private final LoggingEventBuilder logBuilder; private final int contentLength; private final ClientLogger logger; private final boolean prettyPrintBody; private final String contentTypeHeader; private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, int contentLength, String contentTypeHeader, boolean prettyPrintBody) { super(actualResponse.getRequest()); this.actualResponse = actualResponse; this.logBuilder = logBuilder; this.logger = logger; this.contentLength = contentLength; this.contentTypeHeader = contentTypeHeader; this.prettyPrintBody = prettyPrintBody; } @Override public int getStatusCode() { return actualResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return actualResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return actualResponse.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); return actualResponse.getBody() .doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }) .doFinally(ignored -> doLog(stream.toString(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); } @Override public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(String::new); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override private void doLog(String body) { logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) .log(RESPONSE_LOG_MESSAGE); } }
class LoggingHttpResponse extends HttpResponse { private final HttpResponse actualResponse; private final LoggingEventBuilder logBuilder; private final int contentLength; private final ClientLogger logger; private final boolean prettyPrintBody; private final String contentTypeHeader; private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, int contentLength, String contentTypeHeader, boolean prettyPrintBody) { super(actualResponse.getRequest()); this.actualResponse = actualResponse; this.logBuilder = logBuilder; this.logger = logger; this.contentLength = contentLength; this.contentTypeHeader = contentTypeHeader; this.prettyPrintBody = prettyPrintBody; } @Override public int getStatusCode() { return actualResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return actualResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return actualResponse.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); return actualResponse.getBody() .doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }) .doFinally(ignored -> doLog(stream.toString(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); } @Override public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(String::new); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override private void doLog(String body) { logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) .log(RESPONSE_LOG_MESSAGE); } }
To make body logging synchronous: `getBodyAsBinaryData` is the only sync way to get the response body and default implementation is async https://github.com/Azure/azure-sdk-for-java/blob/1cb5a6a84f86f7cce5f0fa287b3980c5c4507ab3/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpResponse.java#L89-L92
public BinaryData getBodyAsBinaryData() { BinaryData content = actualResponse.getBodyAsBinaryData(); doLog(content.toString()); return content; }
doLog(content.toString());
public BinaryData getBodyAsBinaryData() { BinaryData content = actualResponse.getBodyAsBinaryData(); doLog(content.toString()); return content; }
class LoggingHttpResponse extends HttpResponse { private final HttpResponse actualResponse; private final LoggingEventBuilder logBuilder; private final int contentLength; private final ClientLogger logger; private final boolean prettyPrintBody; private final String contentTypeHeader; private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, int contentLength, String contentTypeHeader, boolean prettyPrintBody) { super(actualResponse.getRequest()); this.actualResponse = actualResponse; this.logBuilder = logBuilder; this.logger = logger; this.contentLength = contentLength; this.contentTypeHeader = contentTypeHeader; this.prettyPrintBody = prettyPrintBody; } @Override public int getStatusCode() { return actualResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return actualResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return actualResponse.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); return actualResponse.getBody() .doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }) .doFinally(ignored -> doLog(stream.toString(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); } @Override public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(String::new); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override private void doLog(String body) { logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) .log(RESPONSE_LOG_MESSAGE); } }
class LoggingHttpResponse extends HttpResponse { private final HttpResponse actualResponse; private final LoggingEventBuilder logBuilder; private final int contentLength; private final ClientLogger logger; private final boolean prettyPrintBody; private final String contentTypeHeader; private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, int contentLength, String contentTypeHeader, boolean prettyPrintBody) { super(actualResponse.getRequest()); this.actualResponse = actualResponse; this.logBuilder = logBuilder; this.logger = logger; this.contentLength = contentLength; this.contentTypeHeader = contentTypeHeader; this.prettyPrintBody = prettyPrintBody; } @Override public int getStatusCode() { return actualResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return actualResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return actualResponse.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); return actualResponse.getBody() .doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }) .doFinally(ignored -> doLog(stream.toString(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); } @Override public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(String::new); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override private void doLog(String body) { logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) .log(RESPONSE_LOG_MESSAGE); } }
Should we eagerly call `content.toString()` here? Instead we should consider passing the `content` to doLog() method and there, we can use the supplier methods ClientLogger provides to log if logging is enabled - `logBuilder.addKeyValue(BODY_KEY, () -> content.toString())`.
public BinaryData getBodyAsBinaryData() { BinaryData content = actualResponse.getBodyAsBinaryData(); doLog(content.toString()); return content; }
doLog(content.toString());
public BinaryData getBodyAsBinaryData() { BinaryData content = actualResponse.getBodyAsBinaryData(); doLog(content.toString()); return content; }
class LoggingHttpResponse extends HttpResponse { private final HttpResponse actualResponse; private final LoggingEventBuilder logBuilder; private final int contentLength; private final ClientLogger logger; private final boolean prettyPrintBody; private final String contentTypeHeader; private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, int contentLength, String contentTypeHeader, boolean prettyPrintBody) { super(actualResponse.getRequest()); this.actualResponse = actualResponse; this.logBuilder = logBuilder; this.logger = logger; this.contentLength = contentLength; this.contentTypeHeader = contentTypeHeader; this.prettyPrintBody = prettyPrintBody; } @Override public int getStatusCode() { return actualResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return actualResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return actualResponse.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); return actualResponse.getBody() .doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }) .doFinally(ignored -> doLog(stream.toString(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); } @Override public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(String::new); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override private void doLog(String body) { logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) .log(RESPONSE_LOG_MESSAGE); } }
class LoggingHttpResponse extends HttpResponse { private final HttpResponse actualResponse; private final LoggingEventBuilder logBuilder; private final int contentLength; private final ClientLogger logger; private final boolean prettyPrintBody; private final String contentTypeHeader; private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, int contentLength, String contentTypeHeader, boolean prettyPrintBody) { super(actualResponse.getRequest()); this.actualResponse = actualResponse; this.logBuilder = logBuilder; this.logger = logger; this.contentLength = contentLength; this.contentTypeHeader = contentTypeHeader; this.prettyPrintBody = prettyPrintBody; } @Override public int getStatusCode() { return actualResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return actualResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return actualResponse.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); return actualResponse.getBody() .doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }) .doFinally(ignored -> doLog(stream.toString(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); } @Override public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(String::new); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override private void doLog(String body) { logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) .log(RESPONSE_LOG_MESSAGE); } }
`LoggingHttpResponse` is created only if logging at that level is enabled, body logging is enabled and content type is not a stream, so there is no need to do lazy `toString` - there are no checks in `doLog` method. https://github.com/Azure/azure-sdk-for-java/blob/41038467140a89185d27ee9a0857a59acad0ef61/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java#L300-L315
public BinaryData getBodyAsBinaryData() { BinaryData content = actualResponse.getBodyAsBinaryData(); doLog(content.toString()); return content; }
doLog(content.toString());
public BinaryData getBodyAsBinaryData() { BinaryData content = actualResponse.getBodyAsBinaryData(); doLog(content.toString()); return content; }
class LoggingHttpResponse extends HttpResponse { private final HttpResponse actualResponse; private final LoggingEventBuilder logBuilder; private final int contentLength; private final ClientLogger logger; private final boolean prettyPrintBody; private final String contentTypeHeader; private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, int contentLength, String contentTypeHeader, boolean prettyPrintBody) { super(actualResponse.getRequest()); this.actualResponse = actualResponse; this.logBuilder = logBuilder; this.logger = logger; this.contentLength = contentLength; this.contentTypeHeader = contentTypeHeader; this.prettyPrintBody = prettyPrintBody; } @Override public int getStatusCode() { return actualResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return actualResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return actualResponse.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); return actualResponse.getBody() .doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }) .doFinally(ignored -> doLog(stream.toString(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); } @Override public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(String::new); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override private void doLog(String body) { logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) .log(RESPONSE_LOG_MESSAGE); } }
class LoggingHttpResponse extends HttpResponse { private final HttpResponse actualResponse; private final LoggingEventBuilder logBuilder; private final int contentLength; private final ClientLogger logger; private final boolean prettyPrintBody; private final String contentTypeHeader; private LoggingHttpResponse(HttpResponse actualResponse, LoggingEventBuilder logBuilder, ClientLogger logger, int contentLength, String contentTypeHeader, boolean prettyPrintBody) { super(actualResponse.getRequest()); this.actualResponse = actualResponse; this.logBuilder = logBuilder; this.logger = logger; this.contentLength = contentLength; this.contentTypeHeader = contentTypeHeader; this.prettyPrintBody = prettyPrintBody; } @Override public int getStatusCode() { return actualResponse.getStatusCode(); } @Override public String getHeaderValue(String name) { return actualResponse.getHeaderValue(name); } @Override public HttpHeaders getHeaders() { return actualResponse.getHeaders(); } @Override public Flux<ByteBuffer> getBody() { AccessibleByteArrayOutputStream stream = new AccessibleByteArrayOutputStream(contentLength); return actualResponse.getBody() .doOnNext(byteBuffer -> { try { ImplUtils.writeByteBufferToStream(byteBuffer.duplicate(), stream); } catch (IOException ex) { throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } }) .doFinally(ignored -> doLog(stream.toString(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return FluxUtil.collectBytesFromNetworkResponse(getBody(), actualResponse.getHeaders()); } @Override public Mono<String> getBodyAsString() { return getBodyAsByteArray().map(String::new); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } @Override private void doLog(String body) { logBuilder.addKeyValue(LoggingKeys.BODY_KEY, prettyPrintIfNeeded(logger, prettyPrintBody, contentTypeHeader, body)) .log(RESPONSE_LOG_MESSAGE); } }
Missing throw Javadoc for this
public SyncOperationResourcePollingStrategy(HttpHeaderName operationLocationHeaderName, PollingStrategyOptions pollingStrategyOptions) { Objects.requireNonNull(pollingStrategyOptions, "'pollingStrategyOptions' cannot be null"); this.httpPipeline = pollingStrategyOptions.getHttpPipeline(); this.endpoint = pollingStrategyOptions.getEndpoint(); this.serializer = pollingStrategyOptions.getSerializer() != null ? pollingStrategyOptions.getSerializer() : new DefaultJsonSerializer(); this.operationLocationHeaderName = (operationLocationHeaderName == null) ? DEFAULT_OPERATION_LOCATION_HEADER : operationLocationHeaderName; this.serviceVersion = pollingStrategyOptions.getServiceVersion(); this.context = pollingStrategyOptions.getContext() == null ? Context.NONE : pollingStrategyOptions.getContext(); }
Objects.requireNonNull(pollingStrategyOptions, "'pollingStrategyOptions' cannot be null");
public SyncOperationResourcePollingStrategy(HttpHeaderName operationLocationHeaderName, PollingStrategyOptions pollingStrategyOptions) { Objects.requireNonNull(pollingStrategyOptions, "'pollingStrategyOptions' cannot be null"); this.httpPipeline = pollingStrategyOptions.getHttpPipeline(); this.endpoint = pollingStrategyOptions.getEndpoint(); this.serializer = pollingStrategyOptions.getSerializer() != null ? pollingStrategyOptions.getSerializer() : new DefaultJsonSerializer(); this.operationLocationHeaderName = (operationLocationHeaderName == null) ? DEFAULT_OPERATION_LOCATION_HEADER : operationLocationHeaderName; this.serviceVersion = pollingStrategyOptions.getServiceVersion(); this.context = pollingStrategyOptions.getContext() == null ? Context.NONE : pollingStrategyOptions.getContext(); }
class SyncOperationResourcePollingStrategy<T, U> implements SyncPollingStrategy<T, U> { private static final ClientLogger LOGGER = new ClientLogger(SyncOperationResourcePollingStrategy.class); private static final HttpHeaderName DEFAULT_OPERATION_LOCATION_HEADER = HttpHeaderName.fromString("Operation-Location"); private static final TypeReference<PollResult> POLL_RESULT_TYPE_REFERENCE = TypeReference.createInstance(PollResult.class); private final HttpPipeline httpPipeline; private final ObjectSerializer serializer; private final String endpoint; private final HttpHeaderName operationLocationHeaderName; private final Context context; private final String serviceVersion; /** * Creates an instance of the operation resource polling strategy using a JSON serializer and "Operation-Location" * as the header for polling. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with */ public SyncOperationResourcePollingStrategy(HttpPipeline httpPipeline) { this(DEFAULT_OPERATION_LOCATION_HEADER, new PollingStrategyOptions(httpPipeline)); } /** * Creates an instance of the operation resource polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @param serializer a custom serializer for serializing and deserializing polling responses * @param operationLocationHeaderName a custom header for polling the long-running operation */ public SyncOperationResourcePollingStrategy(HttpPipeline httpPipeline, ObjectSerializer serializer, String operationLocationHeaderName) { this(httpPipeline, serializer, operationLocationHeaderName, Context.NONE); } /** * Creates an instance of the operation resource polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @param serializer a custom serializer for serializing and deserializing polling responses * @param operationLocationHeaderName a custom header for polling the long-running operation * @param context an instance of {@link com.azure.core.util.Context} */ public SyncOperationResourcePollingStrategy(HttpPipeline httpPipeline, ObjectSerializer serializer, String operationLocationHeaderName, Context context) { this(httpPipeline, null, serializer, operationLocationHeaderName, context); } /** * Creates an instance of the operation resource polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with. * @param endpoint an endpoint for creating an absolute path when the path itself is relative. * @param serializer a custom serializer for serializing and deserializing polling responses. * @param operationLocationHeaderName a custom header for polling the long-running operation. * @param context an instance of {@link com.azure.core.util.Context}. */ public SyncOperationResourcePollingStrategy(HttpPipeline httpPipeline, String endpoint, ObjectSerializer serializer, String operationLocationHeaderName, Context context) { this(operationLocationHeaderName == null ? null : HttpHeaderName.fromString(operationLocationHeaderName), new PollingStrategyOptions(httpPipeline) .setEndpoint(endpoint) .setSerializer(serializer) .setContext(context)); } /** * Creates an instance of the operation resource polling strategy. * * @param operationLocationHeaderName a custom header for polling the long-running operation. * @param pollingStrategyOptions options to configure this polling strategy. */ @Override public boolean canPoll(Response<?> initialResponse) { HttpHeader operationLocationHeader = initialResponse.getHeaders().get(operationLocationHeaderName); if (operationLocationHeader != null) { try { new URL(getAbsolutePath(operationLocationHeader.getValue(), endpoint, LOGGER)); return true; } catch (MalformedURLException e) { return false; } } return false; } @Override public PollResponse<T> onInitialResponse(Response<?> response, PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { HttpHeader operationLocationHeader = response.getHeaders().get(operationLocationHeaderName); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); if (operationLocationHeader != null) { pollingContext.setData(operationLocationHeaderName.getCaseSensitiveName(), getAbsolutePath(operationLocationHeader.getValue(), endpoint, LOGGER)); } if (locationHeader != null) { pollingContext.setData(PollingConstants.LOCATION, getAbsolutePath(locationHeader.getValue(), endpoint, LOGGER)); } pollingContext.setData(PollingConstants.HTTP_METHOD, response.getRequest().getHttpMethod().name()); pollingContext.setData(PollingConstants.REQUEST_URL, response.getRequest().getUrl().toString()); if (response.getStatusCode() == 200 || response.getStatusCode() == 201 || response.getStatusCode() == 202 || response.getStatusCode() == 204) { Duration retryAfter = ImplUtils.getRetryAfterFromHeaders(response.getHeaders(), OffsetDateTime::now); return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, PollingUtils.convertResponseSync(response.getValue(), serializer, pollResponseType), retryAfter); } throw LOGGER.logExceptionAsError(new AzureException(String.format( "Operation failed or cancelled with status code %d, '%s' header: %s, and response body: %s", response.getStatusCode(), operationLocationHeaderName, operationLocationHeader, PollingUtils.serializeResponseSync(response.getValue(), serializer)))); } @Override public PollResponse<T> poll(PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { String url = pollingContext.getData(operationLocationHeaderName .getCaseSensitiveName()); url = setServiceVersionQueryParam(url); HttpRequest request = new HttpRequest(HttpMethod.GET, url); try (HttpResponse response = httpPipeline.sendSync(request, context)) { BinaryData responseBody = response.getBodyAsBinaryData(); PollResult pollResult = PollingUtils.deserializeResponseSync(responseBody, serializer, POLL_RESULT_TYPE_REFERENCE); String resourceLocation = pollResult.getResourceLocation(); if (resourceLocation != null) { pollingContext.setData(PollingConstants.RESOURCE_LOCATION, getAbsolutePath(resourceLocation, endpoint, LOGGER)); } pollingContext.setData(PollingConstants.POLL_RESPONSE_BODY, responseBody.toString()); Duration retryAfter = ImplUtils.getRetryAfterFromHeaders(response.getHeaders(), OffsetDateTime::now); return new PollResponse<>(pollResult.getStatus(), PollingUtils.deserializeResponseSync(responseBody, serializer, pollResponseType), retryAfter); } } @Override public U getResult(PollingContext<T> pollingContext, TypeReference<U> resultType) { if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.FAILED) { throw LOGGER.logExceptionAsError(new AzureException("Long running operation failed.")); } else if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.USER_CANCELLED) { throw LOGGER.logExceptionAsError(new AzureException("Long running operation cancelled.")); } String finalGetUrl = pollingContext.getData(PollingConstants.RESOURCE_LOCATION); if (finalGetUrl == null) { String httpMethod = pollingContext.getData(PollingConstants.HTTP_METHOD); if (HttpMethod.PUT.name().equalsIgnoreCase(httpMethod) || HttpMethod.PATCH.name().equalsIgnoreCase(httpMethod)) { finalGetUrl = pollingContext.getData(PollingConstants.REQUEST_URL); } else if (HttpMethod.POST.name().equalsIgnoreCase(httpMethod)) { finalGetUrl = pollingContext.getData(PollingConstants.LOCATION); } else { throw LOGGER.logExceptionAsError(new AzureException("Cannot get final result")); } } if (finalGetUrl == null) { String latestResponseBody = pollingContext.getData(PollingConstants.POLL_RESPONSE_BODY); return PollingUtils.deserializeResponseSync(BinaryData.fromString(latestResponseBody), serializer, resultType); } finalGetUrl = setServiceVersionQueryParam(finalGetUrl); HttpRequest request = new HttpRequest(HttpMethod.GET, finalGetUrl); try (HttpResponse response = httpPipeline.sendSync(request, context)) { BinaryData responseBody = response.getBodyAsBinaryData(); return PollingUtils.deserializeResponseSync(responseBody, serializer, resultType); } } private String setServiceVersionQueryParam(String url) { if (!CoreUtils.isNullOrEmpty(this.serviceVersion)) { UrlBuilder urlBuilder = UrlBuilder.parse(url); urlBuilder.setQueryParameter("api-version", this.serviceVersion); url = urlBuilder.toString(); } return url; } }
class SyncOperationResourcePollingStrategy<T, U> implements SyncPollingStrategy<T, U> { private static final ClientLogger LOGGER = new ClientLogger(SyncOperationResourcePollingStrategy.class); private static final HttpHeaderName DEFAULT_OPERATION_LOCATION_HEADER = HttpHeaderName.fromString("Operation-Location"); private static final TypeReference<PollResult> POLL_RESULT_TYPE_REFERENCE = TypeReference.createInstance(PollResult.class); private final HttpPipeline httpPipeline; private final ObjectSerializer serializer; private final String endpoint; private final HttpHeaderName operationLocationHeaderName; private final Context context; private final String serviceVersion; /** * Creates an instance of the operation resource polling strategy using a JSON serializer and "Operation-Location" * as the header for polling. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with */ public SyncOperationResourcePollingStrategy(HttpPipeline httpPipeline) { this(DEFAULT_OPERATION_LOCATION_HEADER, new PollingStrategyOptions(httpPipeline)); } /** * Creates an instance of the operation resource polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @param serializer a custom serializer for serializing and deserializing polling responses * @param operationLocationHeaderName a custom header for polling the long-running operation */ public SyncOperationResourcePollingStrategy(HttpPipeline httpPipeline, ObjectSerializer serializer, String operationLocationHeaderName) { this(httpPipeline, serializer, operationLocationHeaderName, Context.NONE); } /** * Creates an instance of the operation resource polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with * @param serializer a custom serializer for serializing and deserializing polling responses * @param operationLocationHeaderName a custom header for polling the long-running operation * @param context an instance of {@link com.azure.core.util.Context} */ public SyncOperationResourcePollingStrategy(HttpPipeline httpPipeline, ObjectSerializer serializer, String operationLocationHeaderName, Context context) { this(httpPipeline, null, serializer, operationLocationHeaderName, context); } /** * Creates an instance of the operation resource polling strategy. * * @param httpPipeline an instance of {@link HttpPipeline} to send requests with. * @param endpoint an endpoint for creating an absolute path when the path itself is relative. * @param serializer a custom serializer for serializing and deserializing polling responses. * @param operationLocationHeaderName a custom header for polling the long-running operation. * @param context an instance of {@link com.azure.core.util.Context}. */ public SyncOperationResourcePollingStrategy(HttpPipeline httpPipeline, String endpoint, ObjectSerializer serializer, String operationLocationHeaderName, Context context) { this(operationLocationHeaderName == null ? null : HttpHeaderName.fromString(operationLocationHeaderName), new PollingStrategyOptions(httpPipeline) .setEndpoint(endpoint) .setSerializer(serializer) .setContext(context)); } /** * Creates an instance of the operation resource polling strategy. * * @param operationLocationHeaderName a custom header for polling the long-running operation. * @param pollingStrategyOptions options to configure this polling strategy. * @throws NullPointerException if {@code pollingStrategyOptions} is null. */ @Override public boolean canPoll(Response<?> initialResponse) { HttpHeader operationLocationHeader = initialResponse.getHeaders().get(operationLocationHeaderName); if (operationLocationHeader != null) { try { new URL(getAbsolutePath(operationLocationHeader.getValue(), endpoint, LOGGER)); return true; } catch (MalformedURLException e) { return false; } } return false; } @Override public PollResponse<T> onInitialResponse(Response<?> response, PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { HttpHeader operationLocationHeader = response.getHeaders().get(operationLocationHeaderName); HttpHeader locationHeader = response.getHeaders().get(HttpHeaderName.LOCATION); if (operationLocationHeader != null) { pollingContext.setData(operationLocationHeaderName.getCaseSensitiveName(), getAbsolutePath(operationLocationHeader.getValue(), endpoint, LOGGER)); } if (locationHeader != null) { pollingContext.setData(PollingConstants.LOCATION, getAbsolutePath(locationHeader.getValue(), endpoint, LOGGER)); } pollingContext.setData(PollingConstants.HTTP_METHOD, response.getRequest().getHttpMethod().name()); pollingContext.setData(PollingConstants.REQUEST_URL, response.getRequest().getUrl().toString()); if (response.getStatusCode() == 200 || response.getStatusCode() == 201 || response.getStatusCode() == 202 || response.getStatusCode() == 204) { Duration retryAfter = ImplUtils.getRetryAfterFromHeaders(response.getHeaders(), OffsetDateTime::now); return new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, PollingUtils.convertResponseSync(response.getValue(), serializer, pollResponseType), retryAfter); } throw LOGGER.logExceptionAsError(new AzureException(String.format( "Operation failed or cancelled with status code %d, '%s' header: %s, and response body: %s", response.getStatusCode(), operationLocationHeaderName, operationLocationHeader, PollingUtils.serializeResponseSync(response.getValue(), serializer)))); } @Override public PollResponse<T> poll(PollingContext<T> pollingContext, TypeReference<T> pollResponseType) { String url = pollingContext.getData(operationLocationHeaderName .getCaseSensitiveName()); url = setServiceVersionQueryParam(url); HttpRequest request = new HttpRequest(HttpMethod.GET, url); try (HttpResponse response = httpPipeline.sendSync(request, context)) { BinaryData responseBody = response.getBodyAsBinaryData(); PollResult pollResult = PollingUtils.deserializeResponseSync(responseBody, serializer, POLL_RESULT_TYPE_REFERENCE); String resourceLocation = pollResult.getResourceLocation(); if (resourceLocation != null) { pollingContext.setData(PollingConstants.RESOURCE_LOCATION, getAbsolutePath(resourceLocation, endpoint, LOGGER)); } pollingContext.setData(PollingConstants.POLL_RESPONSE_BODY, responseBody.toString()); Duration retryAfter = ImplUtils.getRetryAfterFromHeaders(response.getHeaders(), OffsetDateTime::now); return new PollResponse<>(pollResult.getStatus(), PollingUtils.deserializeResponseSync(responseBody, serializer, pollResponseType), retryAfter); } } @Override public U getResult(PollingContext<T> pollingContext, TypeReference<U> resultType) { if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.FAILED) { throw LOGGER.logExceptionAsError(new AzureException("Long running operation failed.")); } else if (pollingContext.getLatestResponse().getStatus() == LongRunningOperationStatus.USER_CANCELLED) { throw LOGGER.logExceptionAsError(new AzureException("Long running operation cancelled.")); } String finalGetUrl = pollingContext.getData(PollingConstants.RESOURCE_LOCATION); if (finalGetUrl == null) { String httpMethod = pollingContext.getData(PollingConstants.HTTP_METHOD); if (HttpMethod.PUT.name().equalsIgnoreCase(httpMethod) || HttpMethod.PATCH.name().equalsIgnoreCase(httpMethod)) { finalGetUrl = pollingContext.getData(PollingConstants.REQUEST_URL); } else if (HttpMethod.POST.name().equalsIgnoreCase(httpMethod)) { finalGetUrl = pollingContext.getData(PollingConstants.LOCATION); } else { throw LOGGER.logExceptionAsError(new AzureException("Cannot get final result")); } } if (finalGetUrl == null) { String latestResponseBody = pollingContext.getData(PollingConstants.POLL_RESPONSE_BODY); return PollingUtils.deserializeResponseSync(BinaryData.fromString(latestResponseBody), serializer, resultType); } finalGetUrl = setServiceVersionQueryParam(finalGetUrl); HttpRequest request = new HttpRequest(HttpMethod.GET, finalGetUrl); try (HttpResponse response = httpPipeline.sendSync(request, context)) { BinaryData responseBody = response.getBodyAsBinaryData(); return PollingUtils.deserializeResponseSync(responseBody, serializer, resultType); } } private String setServiceVersionQueryParam(String url) { if (!CoreUtils.isNullOrEmpty(this.serviceVersion)) { UrlBuilder urlBuilder = UrlBuilder.parse(url); urlBuilder.setQueryParameter("api-version", this.serviceVersion); url = urlBuilder.toString(); } return url; } }
delete
public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2023, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); }
public void canUseSasTokenToCreateValidTableClient() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Skipping Cosmos test."); final OffsetDateTime expiryTime = OffsetDateTime.of(2023, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("a"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(tableClient.getTableEndpoint()) .sasToken(sas) .tableName(tableClient.getTableName()); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); }
class TableAsyncClientTest extends TableClientTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; protected HttpClient buildAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test public void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } /** * Tests that a table and entity can be created while having a different tenant ID than the one that will be * provided in the authentication challenge. */ @Test public void createTableWithMultipleTenants() { Assumptions.assumeTrue(tableClient.getTableEndpoint().contains("core.windows.net") && tableClient.getServiceVersion() == TableServiceVersion.V2020_12_06); final String tableName2 = testResourceNamer.randomName("tableName", 20); final ClientSecretCredential credential = new ClientSecretCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get("TABLES_CLIENT_ID", "clientId")) .clientSecret(Configuration.getGlobalConfiguration().get("TABLES_CLIENT_SECRET", "clientSecret")) .tenantId(testResourceNamer.randomUuid()) .additionallyAllowedTenants("*") .build(); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, Configuration.getGlobalConfiguration().get("TABLES_ENDPOINT", "https: StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient2.createEntity(tableEntity)) .expectComplete() .verify(); } @Test public void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test public void createEntity() { createEntityImpl("partitionKey", "rowKey"); } @Test public void createEntityWithSingleQuotesInPartitionKey() { createEntityImpl("partition'Key", "rowKey"); } @Test public void createEntityWithSingleQuotesInRowKey() { createEntityImpl("partitionKey", "row'Key"); } private void createEntityImpl(String partitionKeyPrefix, String rowKeyPrefix) { final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test public void createEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void createEntityWithAllSupportedDataTypes() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test public void createEntitySubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test public void deleteTable() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test public void deleteNonExistingTable() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test public void deleteTableWithResponse() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test public void deleteNonExistingTableWithResponse() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void deleteEntity() { deleteEntityImpl("partitionKey", "rowKey"); } @Test public void deleteEntityWithSingleQuotesInPartitionKey() { deleteEntityImpl("partition'Key", "rowKey"); } @Test public void deleteEntityWithSingleQuotesInRowKey() { deleteEntityImpl("partitionKey", "row'Key"); } private void deleteEntityImpl(String partitionKeyPrefix, String rowKeyPrefix) { final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test public void deleteNonExistingEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test public void deleteEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void deleteNonExistingEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void deleteEntityWithResponseMatchETag() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void getEntityWithSingleQuotesInPartitionKey() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer, "partition'Key", "rowKey"); } @Test public void getEntityWithSingleQuotesInRowKey() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer, "partitionKey", "row'Key"); } @Test public void getEntityWithResponse() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer, "partitionKey", "rowKey"); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer, String partitionKeyPrefix, String rowKeyPrefix) { final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test public void getEntityWithResponseWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test public void updateEntityWithSingleQuotesInPartitionKey() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE, "partition'Key", "rowKey"); } @Test public void updateEntityWithSingleQuotesInRowKey() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE, "partitionKey", "row'Key"); } /*@Test public void getEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test public void updateEntityWithResponseReplace() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE, "partitionKey", "rowKey"); } @Test public void updateEntityWithResponseMerge() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE, "partitionKey", "rowKey"); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode, String partitionKeyPrefix, String rowKeyPrefix) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test public void updateEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test public void listEntities() { listEntitiesImpl("partitionKey", "rowKey"); } @Test public void listEntitiesWithSingleQuotesInPartitionKey() { listEntitiesImpl("partition'Key", "rowKey"); } @Test public void listEntitiesWithSingleQuotesInRowKey() { listEntitiesImpl("partitionKey", "row'Key"); } private void listEntitiesImpl(String partitionKeyPrefix, String rowKeyPrefix) { final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final String rowKeyValue2 = testResourceNamer.randomName(rowKeyPrefix, 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test public void listEntitiesWithFilter() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test public void listEntitiesWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test public void listEntitiesWithTop() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test public void listEntitiesSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test public void submitTransaction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test public void submitTransactionAllActions() { submitTransactionAllActionsImpl("partitionKey", "rowKey"); } @Test public void submitTransactionAllActionsForEntitiesWithSingleQuotesInPartitionKey() { submitTransactionAllActionsImpl("partition'Key", "rowKey"); } @Test public void submitTransactionAllActionsForEntitiesWithSingleQuotesInRowKey() { submitTransactionAllActionsImpl("partitionKey", "row'Key"); } private void submitTransactionAllActionsImpl(String partitionKeyPrefix, String rowKeyPrefix) { String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); String rowKeyValueCreate = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueDelete = testResourceNamer.randomName(rowKeyPrefix, 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test public void submitTransactionWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test public void submitTransactionWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } } @Test public void submitTransactionWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
class TableAsyncClientTest extends TableClientTestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; protected HttpClient buildAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); tableClient = getClientBuilder(tableName, connectionString).buildAsyncClient(); tableClient.createTable().block(TIMEOUT); } @Test public void createTable() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); } /** * Tests that a table and entity can be created while having a different tenant ID than the one that will be * provided in the authentication challenge. */ @Test public void createTableWithMultipleTenants() { Assumptions.assumeTrue(tableClient.getTableEndpoint().contains("core.windows.net") && tableClient.getServiceVersion() == TableServiceVersion.V2020_12_06); final String tableName2 = testResourceNamer.randomName("tableName", 20); TokenCredential credential = null; if (interceptorManager.isPlaybackMode()) { credential = new MockTokenCredential(); } else if (interceptorManager.isRecordMode()) { credential = new ClientSecretCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get("TABLES_CLIENT_ID", "clientId")) .clientSecret(Configuration.getGlobalConfiguration().get("TABLES_CLIENT_SECRET", "clientSecret")) .tenantId(testResourceNamer.randomUuid()) .additionallyAllowedTenants("*") .build(); } final TableAsyncClient tableClient2 = getClientBuilder(tableName2, Configuration.getGlobalConfiguration().get("TABLES_ENDPOINT", "https: StepVerifier.create(tableClient2.createTable()) .assertNext(Assertions::assertNotNull) .expectComplete() .verify(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient2.createEntity(tableEntity)) .expectComplete() .verify(); } @Test public void createTableWithResponse() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableAsyncClient tableClient2 = getClientBuilder(tableName2, connectionString).buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test public void createEntity() { createEntityImpl("partitionKey", "rowKey"); } @Test public void createEntityWithSingleQuotesInPartitionKey() { createEntityImpl("partition'Key", "rowKey"); } @Test public void createEntityWithSingleQuotesInRowKey() { createEntityImpl("partitionKey", "row'Key"); } private void createEntityImpl(String partitionKeyPrefix, String rowKeyPrefix) { final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test public void createEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void createEntityWithAllSupportedDataTypes() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } /*@Test public void createEntitySubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); }*/ @Test public void deleteTable() { StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test public void deleteNonExistingTable() { tableClient.deleteTable().block(); StepVerifier.create(tableClient.deleteTable()) .expectComplete() .verify(); } @Test public void deleteTableWithResponse() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test public void deleteNonExistingTableWithResponse() { final int expectedStatusCode = 404; tableClient.deleteTableWithResponse().block(); StepVerifier.create(tableClient.deleteTableWithResponse()) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void deleteEntity() { deleteEntityImpl("partitionKey", "rowKey"); } @Test public void deleteEntityWithSingleQuotesInPartitionKey() { deleteEntityImpl("partition'Key", "rowKey"); } @Test public void deleteEntityWithSingleQuotesInRowKey() { deleteEntityImpl("partitionKey", "row'Key"); } private void deleteEntityImpl(String partitionKeyPrefix, String rowKeyPrefix) { final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test public void deleteNonExistingEntity() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test public void deleteEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void deleteNonExistingEntityWithResponse() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 404; StepVerifier.create(tableClient.deleteEntityWithResponse(entity, false)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void deleteEntityWithResponseMatchETag() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(createdEntity, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void getEntityWithSingleQuotesInPartitionKey() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer, "partition'Key", "rowKey"); } @Test public void getEntityWithSingleQuotesInRowKey() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer, "partitionKey", "row'Key"); } @Test public void getEntityWithResponse() { getEntityWithResponseAsyncImpl(this.tableClient, this.testResourceNamer, "partitionKey", "rowKey"); } static void getEntityWithResponseAsyncImpl(TableAsyncClient tableClient, TestResourceNamer testResourceNamer, String partitionKeyPrefix, String rowKeyPrefix) { final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test public void getEntityWithResponseWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); List<String> propertyList = new ArrayList<>(); propertyList.add("Test"); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, propertyList)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test public void updateEntityWithSingleQuotesInPartitionKey() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE, "partition'Key", "rowKey"); } @Test public void updateEntityWithSingleQuotesInRowKey() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE, "partitionKey", "row'Key"); } /*@Test public void getEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; final Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.setProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }*/ @Test public void updateEntityWithResponseReplace() { updateEntityWithResponseAsync(TableEntityUpdateMode.REPLACE, "partitionKey", "rowKey"); } @Test public void updateEntityWithResponseMerge() { updateEntityWithResponseAsync(TableEntityUpdateMode.MERGE, "partitionKey", "rowKey"); } /** * In the case of {@link TableEntityUpdateMode * In the case of {@link TableEntityUpdateMode */ void updateEntityWithResponseAsync(TableEntityUpdateMode mode, String partitionKeyPrefix, String rowKeyPrefix) { final boolean expectOldProperty = mode == TableEntityUpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, mode, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } /*@Test public void updateEntityWithResponseSubclass() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, TableEntityUpdateMode.REPLACE, true)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }*/ @Test public void listEntities() { listEntitiesImpl("partitionKey", "rowKey"); } @Test public void listEntitiesWithSingleQuotesInPartitionKey() { listEntitiesImpl("partition'Key", "rowKey"); } @Test public void listEntitiesWithSingleQuotesInRowKey() { listEntitiesImpl("partitionKey", "row'Key"); } private void listEntitiesImpl(String partitionKeyPrefix, String rowKeyPrefix) { final String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); final String rowKeyValue = testResourceNamer.randomName(rowKeyPrefix, 20); final String rowKeyValue2 = testResourceNamer.randomName(rowKeyPrefix, 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test public void listEntitiesWithFilter() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test public void listEntitiesWithSelect() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); List<String> propertyList = new ArrayList<>(); propertyList.add("propertyC"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect(propertyList); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test public void listEntitiesWithTop() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } /*@Test public void listEntitiesSubclass() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); }*/ @Test public void submitTransaction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue2))); final Response<TableTransactionResult> result = tableClient.submitTransactionWithResponse(transactionalBatch).block(TIMEOUT); assertNotNull(result); assertEquals(expectedBatchStatusCode, result.getStatusCode()); assertEquals(transactionalBatch.size(), result.getValue().getTransactionActionResponses().size()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(0).getStatusCode()); assertEquals(expectedOperationStatusCode, result.getValue().getTransactionActionResponses().get(1).getStatusCode()); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertNotNull(entity); assertEquals(partitionKeyValue, entity.getPartitionKey()); assertEquals(rowKeyValue, entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test public void submitTransactionAllActions() { submitTransactionAllActionsImpl("partitionKey", "rowKey"); } @Test public void submitTransactionAllActionsForEntitiesWithSingleQuotesInPartitionKey() { submitTransactionAllActionsImpl("partition'Key", "rowKey"); } @Test public void submitTransactionAllActionsForEntitiesWithSingleQuotesInRowKey() { submitTransactionAllActionsImpl("partitionKey", "row'Key"); } private void submitTransactionAllActionsImpl(String partitionKeyPrefix, String rowKeyPrefix) { String partitionKeyValue = testResourceNamer.randomName(partitionKeyPrefix, 20); String rowKeyValueCreate = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpsertInsert = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpsertMerge = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpsertReplace = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpdateMerge = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueUpdateReplace = testResourceNamer.randomName(rowKeyPrefix, 20); String rowKeyValueDelete = testResourceNamer.randomName(rowKeyPrefix, 20); int expectedBatchStatusCode = 202; int expectedOperationStatusCode = 204; tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValueDelete)).block(TIMEOUT); TableEntity toUpsertMerge = new TableEntity(partitionKeyValue, rowKeyValueUpsertMerge); toUpsertMerge.addProperty("Test", "MergedValue"); TableEntity toUpsertReplace = new TableEntity(partitionKeyValue, rowKeyValueUpsertReplace); toUpsertReplace.addProperty("Test", "ReplacedValue"); TableEntity toUpdateMerge = new TableEntity(partitionKeyValue, rowKeyValueUpdateMerge); toUpdateMerge.addProperty("Test", "MergedValue"); TableEntity toUpdateReplace = new TableEntity(partitionKeyValue, rowKeyValueUpdateReplace); toUpdateReplace.addProperty("Test", "MergedValue"); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValueCreate))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, new TableEntity(partitionKeyValue, rowKeyValueUpsertInsert))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_MERGE, toUpsertMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPSERT_REPLACE, toUpsertReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_MERGE, toUpdateMerge)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.UPDATE_REPLACE, toUpdateReplace)); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValueDelete))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .assertNext(response -> { assertNotNull(response); assertEquals(expectedBatchStatusCode, response.getStatusCode()); TableTransactionResult result = response.getValue(); assertEquals(transactionalBatch.size(), result.getTransactionActionResponses().size()); for (TableTransactionActionResponse subResponse : result.getTransactionActionResponses()) { assertEquals(expectedOperationStatusCode, subResponse.getStatusCode()); } }) .expectComplete() .verify(); } @Test public void submitTransactionWithFailingAction() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction(TableTransactionActionType.DELETE, new TableEntity(partitionKeyValue, rowKeyValue2))); StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("DeleteEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } @Test public void submitTransactionWithSameRowKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableServiceException && e.getMessage().contains("Status code 400") && e.getMessage().contains("InvalidDuplicateRow") && e.getMessage().contains("The batch request contains multiple changes with same row key.") && e.getMessage().contains("An entity can appear only once in a batch request.")) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } } @Test public void submitTransactionWithDifferentPartitionKeys() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String partitionKeyValue2 = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); List<TableTransactionAction> transactionalBatch = new ArrayList<>(); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue, rowKeyValue))); transactionalBatch.add(new TableTransactionAction( TableTransactionActionType.CREATE, new TableEntity(partitionKeyValue2, rowKeyValue2))); if (IS_COSMOS_TEST) { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue) && e.getMessage().contains("rowKey='" + rowKeyValue)) .verify(); } else { StepVerifier.create(tableClient.submitTransactionWithResponse(transactionalBatch)) .expectErrorMatches(e -> e instanceof TableTransactionFailedException && e.getMessage().contains("An action within the operation failed") && e.getMessage().contains("The failed operation was") && e.getMessage().contains("CreateEntity") && e.getMessage().contains("partitionKey='" + partitionKeyValue2) && e.getMessage().contains("rowKey='" + rowKeyValue2)) .verify(); } } @Test public void generateSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("r"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasPermission permissions = TableSasPermission.parse("raud"); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final String startPartitionKey = "startPartitionKey"; final String startRowKey = "startRowKey"; final String endPartitionKey = "endPartitionKey"; final String endRowKey = "endRowKey"; final TableSasSignatureValues sasSignatureValues = new TableSasSignatureValues(expiryTime, permissions) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange) .setStartPartitionKey(startPartitionKey) .setStartRowKey(startRowKey) .setEndPartitionKey(endPartitionKey) .setEndRowKey(endRowKey); final String sas = tableClient.generateSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&tn=" + tableClient.getTableName() + "&sp=raud" + "&spk=startPartitionKey" + "&srk=startRowKey" + "&epk=endPartitionKey" + "&erk=endRowKey" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test @Test public void setAndListAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints."); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id = "testPolicy"; TableSignedIdentifier tableSignedIdentifier = new TableSignedIdentifier(id).setAccessPolicy(tableAccessPolicy); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(Collections.singletonList(tableSignedIdentifier))) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); TableSignedIdentifier signedIdentifier = tableAccessPolicies.getIdentifiers().get(0); assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); assertEquals(id, signedIdentifier.getId()); }) .expectComplete() .verify(); } @Test public void setAndListMultipleAccessPolicies() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and listing access policies is not supported on Cosmos endpoints"); OffsetDateTime startTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); OffsetDateTime expiryTime = OffsetDateTime.of(2022, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); String permissions = "r"; TableAccessPolicy tableAccessPolicy = new TableAccessPolicy() .setStartsOn(startTime) .setExpiresOn(expiryTime) .setPermissions(permissions); String id1 = "testPolicy1"; String id2 = "testPolicy2"; List<TableSignedIdentifier> tableSignedIdentifiers = new ArrayList<>(); tableSignedIdentifiers.add(new TableSignedIdentifier(id1).setAccessPolicy(tableAccessPolicy)); tableSignedIdentifiers.add(new TableSignedIdentifier(id2).setAccessPolicy(tableAccessPolicy)); StepVerifier.create(tableClient.setAccessPoliciesWithResponse(tableSignedIdentifiers)) .assertNext(response -> assertEquals(204, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getAccessPolicies()) .assertNext(tableAccessPolicies -> { assertNotNull(tableAccessPolicies); assertNotNull(tableAccessPolicies.getIdentifiers()); assertEquals(2, tableAccessPolicies.getIdentifiers().size()); assertEquals(id1, tableAccessPolicies.getIdentifiers().get(0).getId()); assertEquals(id2, tableAccessPolicies.getIdentifiers().get(1).getId()); for (TableSignedIdentifier signedIdentifier : tableAccessPolicies.getIdentifiers()) { assertNotNull(signedIdentifier); TableAccessPolicy accessPolicy = signedIdentifier.getAccessPolicy(); assertNotNull(accessPolicy); assertEquals(startTime, accessPolicy.getStartsOn()); assertEquals(expiryTime, accessPolicy.getExpiresOn()); assertEquals(permissions, accessPolicy.getPermissions()); } }) .expectComplete() .verify(); } }
```suggestion customSanitizers.add(new TestProxySanitizer(".*\\\\?(?<query>.*)", "REDACTED", TestProxySanitizerType.URL).setGroupForReplace("query")); ```
public static void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("content-type", ".* boundary=(?<bound>.*)", "REDACTED", TestProxySanitizerType.HEADER).setGroupForReplace("bound")); customSanitizers.add(new TestProxySanitizer(null, ".*\\\\?(?<query>.*)", "REDACTED", TestProxySanitizerType.URL).setGroupForReplace("query")); customSanitizers.add(new TestProxySanitizer("Location", URL_REGEX, "REDACTED", TestProxySanitizerType.HEADER)); customSanitizers.add(new TestProxySanitizer("DataServiceId", URL_REGEX, "REDACTED", TestProxySanitizerType.HEADER)); customSanitizers.add(new TestProxySanitizer(URL_REGEX, "REDACTED", TestProxySanitizerType.BODY_REGEX)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatcher = new ArrayList<>(); customMatcher.add(new TestProxyRequestMatcher(TestProxyRequestMatcherType.BODILESS)); interceptorManager.addMatchers(customMatcher); } }
customSanitizers.add(new TestProxySanitizer(null, ".*\\\\?(?<query>.*)", "REDACTED", TestProxySanitizerType.URL).setGroupForReplace("query"));
public static void addTestProxyTestSanitizersAndMatchers(InterceptorManager interceptorManager) { if (interceptorManager.isLiveMode()) { return; } List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("content-type", ".* boundary=(?<bound>.*)", "REDACTED", TestProxySanitizerType.HEADER).setGroupForReplace("bound")); customSanitizers.add(new TestProxySanitizer(".*\\\\?(?<query>.*)", "REDACTED", TestProxySanitizerType.URL).setGroupForReplace("query")); customSanitizers.add(new TestProxySanitizer("Location", URL_REGEX, "REDACTED", TestProxySanitizerType.HEADER)); customSanitizers.add(new TestProxySanitizer("DataServiceId", URL_REGEX, "REDACTED", TestProxySanitizerType.HEADER)); customSanitizers.add(new TestProxySanitizer(URL_REGEX, "REDACTED", TestProxySanitizerType.BODY_REGEX)); interceptorManager.addSanitizers(customSanitizers); if (interceptorManager.isPlaybackMode()) { List<TestProxyRequestMatcher> customMatcher = new ArrayList<>(); customMatcher.add(new TestProxyRequestMatcher(TestProxyRequestMatcherType.BODILESS)); interceptorManager.addMatchers(customMatcher); } }
class PerRetryPolicy implements HttpPipelinePolicy { @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader("Custom-Header", "Some Value"); return next.process(); } }
class PerRetryPolicy implements HttpPipelinePolicy { @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().setHeader("Custom-Header", "Some Value"); return next.process(); } }
what if user passes in null or a zero second timeout ? should we enforce a min bar ?
public void setDeveloperCredentialTimeout(Duration developerCredentialTimeout) { this.developerCredentialTimeout = developerCredentialTimeout; }
this.developerCredentialTimeout = developerCredentialTimeout;
public void setDeveloperCredentialTimeout(Duration developerCredentialTimeout) { this.developerCredentialTimeout = developerCredentialTimeout; }
class IdentityClientOptions implements Cloneable { private static final ClientLogger LOGGER = new ClientLogger(IdentityClientOptions.class); private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"; public static final String AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"; private String authorityHost; private String imdsAuthorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private UserAssertion userAssertion; private boolean multiTenantAuthDisabled; private Configuration configuration; private IdentityLogOptionsImpl identityLogOptionsImpl; private boolean accountIdentifierLogging; private ManagedIdentityType managedIdentityType; private ManagedIdentityParameters managedIdentityParameters; private Set<String> additionallyAllowedTenants; private ClientOptions clientOptions; private HttpLogOptions httpLogOptions; private RetryOptions retryOptions; private RetryPolicy retryPolicy; private List<HttpPipelinePolicy> perCallPolicies; private List<HttpPipelinePolicy> perRetryPolicies; private boolean instanceDiscovery; private Duration developerCredentialTimeout = Duration.ofSeconds(10); /** * Creates an instance of IdentityClientOptions with default settings. */ public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration().clone(); loadFromConfiguration(configuration); identityLogOptionsImpl = new IdentityLogOptionsImpl(); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); additionallyAllowedTenants = new HashSet<>(); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); instanceDiscovery = true; } /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the AKS Pod Authority endpoint to acquire tokens. */ public String getImdsAuthorityHost() { return imdsAuthorityHost; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Configure the User Assertion Scope to be used for OnBehalfOf Authentication request. * * @param userAssertion the user assertion access token to be used for On behalf Of authentication flow * @return the updated identity client options */ public IdentityClientOptions userAssertion(String userAssertion) { this.userAssertion = new UserAssertion(userAssertion); return this; } /** * Get the configured {@link UserAssertion} * * @return the configured user assertion scope */ public UserAssertion getUserAssertion() { return this.userAssertion; } /** * Gets the status whether multi tenant auth is disabled or not. * @return the flag indicating if multi tenant is disabled or not. */ public boolean isMultiTenantAuthenticationDisabled() { return multiTenantAuthDisabled; } /** * Disable the multi tenant authentication. * @return the updated identity client options */ public IdentityClientOptions disableMultiTenantAuthentication() { this.multiTenantAuthDisabled = true; return this; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiguration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Get the configured Identity Log options. * @return the identity log options. */ public IdentityLogOptionsImpl getIdentityLogOptionsImpl() { return identityLogOptionsImpl; } /** * Set the Identity Log options. * @return the identity log options. */ public IdentityClientOptions setIdentityLogOptionsImpl(IdentityLogOptionsImpl identityLogOptionsImpl) { this.identityLogOptionsImpl = identityLogOptionsImpl; return this; } /** * Set the Managed Identity Type * @param managedIdentityType the Managed Identity Type * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityType(ManagedIdentityType managedIdentityType) { this.managedIdentityType = managedIdentityType; return this; } /** * Get the Managed Identity Type * @return the Managed Identity Type */ public ManagedIdentityType getManagedIdentityType() { return managedIdentityType; } /** * Get the Managed Identity parameters * @return the Managed Identity Parameters */ public ManagedIdentityParameters getManagedIdentityParameters() { return managedIdentityParameters; } /** * Configure the managed identity parameters. * * @param managedIdentityParameters the managed identity parameters to use for authentication. * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityParameters(ManagedIdentityParameters managedIdentityParameters) { this.managedIdentityParameters = managedIdentityParameters; return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed Tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public IdentityClientOptions setAdditionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); return this; } /** * Get the Additionally Allowed Tenants. * @return the List containing additionally allowed tenants. */ public Set<String> getAdditionallyAllowedTenants() { return this.additionallyAllowedTenants; } /** * Configure the client options. * @param clientOptions the client options input. * @return the updated client options */ public IdentityClientOptions setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Get the configured client options. * @return the client options. */ public ClientOptions getClientOptions() { return this.clientOptions; } /** * Configure the client options. * @param httpLogOptions the Http log options input. * @return the updated client options */ public IdentityClientOptions setHttpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Get the configured Http log options. * @return the Http log options. */ public HttpLogOptions getHttpLogOptions() { return this.httpLogOptions; } /** * Configure the retry options. * @param retryOptions the retry options input. * @return the updated client options */ public IdentityClientOptions setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Get the configured retry options. * @return the retry options. */ public RetryOptions getRetryOptions() { return this.retryOptions; } /** * Configure the retry policy. * @param retryPolicy the retry policy. * @return the updated client options */ public IdentityClientOptions setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Get the configured retry policy. * @return the retry policy. */ public RetryPolicy getRetryPolicy() { return this.retryPolicy; } /** * Add a per call policy. * @param httpPipelinePolicy the http pipeline policy to add. * @return the updated client options */ public IdentityClientOptions addPerCallPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perCallPolicies.add(httpPipelinePolicy); return this; } /** * Add a per retry policy. * @param httpPipelinePolicy the retry policy to be added. * @return the updated client options */ public IdentityClientOptions addPerRetryPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perRetryPolicies.add(httpPipelinePolicy); return this; } /** * Get the configured per retry policies. * @return the per retry policies. */ public List<HttpPipelinePolicy> getPerRetryPolicies() { return this.perRetryPolicies; } /** * Get the configured per call policies. * @return the per call policies. */ public List<HttpPipelinePolicy> getPerCallPolicies() { return this.perCallPolicies; } IdentityClientOptions setCp1Disabled(boolean cp1Disabled) { this.cp1Disabled = cp1Disabled; return this; } IdentityClientOptions setMultiTenantAuthDisabled(boolean multiTenantAuthDisabled) { this.multiTenantAuthDisabled = multiTenantAuthDisabled; return this; } IdentityClientOptions setAdditionallyAllowedTenants(Set<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = additionallyAllowedTenants; return this; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } IdentityClientOptions setConfigurationStore(Configuration configuration) { this.configuration = configuration; return this; } IdentityClientOptions setUserAssertion(UserAssertion userAssertion) { this.userAssertion = userAssertion; return this; } IdentityClientOptions setPersistenceCache(boolean persistenceCache) { this.sharedTokenCacheEnabled = persistenceCache; return this; } IdentityClientOptions setImdsAuthorityHost(String imdsAuthorityHost) { this.imdsAuthorityHost = imdsAuthorityHost; return this; } IdentityClientOptions setPerCallPolicies(List<HttpPipelinePolicy> perCallPolicies) { this.perCallPolicies = perCallPolicies; return this; } IdentityClientOptions setPerRetryPolicies(List<HttpPipelinePolicy> perRetryPolicies) { this.perRetryPolicies = perRetryPolicies; return this; } /** * Disable instance discovery. Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return the updated client options */ public IdentityClientOptions disableInstanceDisovery() { this.instanceDiscovery = false; return this; } /** * Gets the instance discovery policy. * @return boolean indicating if instance discovery is enabled. */ public boolean getInstanceDiscovery() { return this.instanceDiscovery; } /** * Loads the details from the specified Configuration Store. */ private void loadFromConfiguration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); imdsAuthorityHost = configuration.get(AZURE_POD_IDENTITY_AUTHORITY_HOST, IdentityConstants.DEFAULT_IMDS_ENDPOINT); ValidationUtil.validateAuthHost(authorityHost, LOGGER); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); multiTenantAuthDisabled = configuration .get(AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH, false); } /** * Gets the timeout to apply to developer credential operations. * @return The timeout value for developer credential operations. */ public Duration getDeveloperCredentialTimeout() { return developerCredentialTimeout; } /** * Sets the timeout for developer credential operations. * @param developerCredentialTimeout The timeout value for developer credential operations. */ public IdentityClientOptions clone() { IdentityClientOptions clone = new IdentityClientOptions() .setAdditionallyAllowedTenants(this.additionallyAllowedTenants) .setAllowUnencryptedCache(this.allowUnencryptedCache) .setHttpClient(this.httpClient) .setAuthenticationRecord(this.authenticationRecord) .setExecutorService(this.executorService) .setIdentityLogOptionsImpl(this.identityLogOptionsImpl) .setTokenCacheOptions(this.tokenCachePersistenceOptions) .setRetryTimeout(this.retryTimeout) .setRegionalAuthority(this.regionalAuthority) .setHttpPipeline(this.httpPipeline) .setIncludeX5c(this.includeX5c) .setProxyOptions(this.proxyOptions) .setMaxRetry(this.maxRetry) .setIntelliJKeePassDatabasePath(this.keePassDatabasePath) .setAuthorityHost(this.authorityHost) .setImdsAuthorityHost(this.imdsAuthorityHost) .setCp1Disabled(this.cp1Disabled) .setMultiTenantAuthDisabled(this.multiTenantAuthDisabled) .setUserAssertion(this.userAssertion) .setConfigurationStore(this.configuration) .setPersistenceCache(this.sharedTokenCacheEnabled) .setClientOptions(this.clientOptions) .setHttpLogOptions(this.httpLogOptions) .setRetryOptions(this.retryOptions) .setRetryPolicy(this.retryPolicy) .setPerCallPolicies(this.perCallPolicies) .setPerRetryPolicies(this.perRetryPolicies); if (!getInstanceDiscovery()) { clone.disableInstanceDisovery(); } return clone; } }
class IdentityClientOptions implements Cloneable { private static final ClientLogger LOGGER = new ClientLogger(IdentityClientOptions.class); private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"; public static final String AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"; private String authorityHost; private String imdsAuthorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private UserAssertion userAssertion; private boolean multiTenantAuthDisabled; private Configuration configuration; private IdentityLogOptionsImpl identityLogOptionsImpl; private boolean accountIdentifierLogging; private ManagedIdentityType managedIdentityType; private ManagedIdentityParameters managedIdentityParameters; private Set<String> additionallyAllowedTenants; private ClientOptions clientOptions; private HttpLogOptions httpLogOptions; private RetryOptions retryOptions; private RetryPolicy retryPolicy; private List<HttpPipelinePolicy> perCallPolicies; private List<HttpPipelinePolicy> perRetryPolicies; private boolean instanceDiscovery; private Duration developerCredentialTimeout = Duration.ofSeconds(10); /** * Creates an instance of IdentityClientOptions with default settings. */ public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration().clone(); loadFromConfiguration(configuration); identityLogOptionsImpl = new IdentityLogOptionsImpl(); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); additionallyAllowedTenants = new HashSet<>(); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); instanceDiscovery = true; } /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the AKS Pod Authority endpoint to acquire tokens. */ public String getImdsAuthorityHost() { return imdsAuthorityHost; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Configure the User Assertion Scope to be used for OnBehalfOf Authentication request. * * @param userAssertion the user assertion access token to be used for On behalf Of authentication flow * @return the updated identity client options */ public IdentityClientOptions userAssertion(String userAssertion) { this.userAssertion = new UserAssertion(userAssertion); return this; } /** * Get the configured {@link UserAssertion} * * @return the configured user assertion scope */ public UserAssertion getUserAssertion() { return this.userAssertion; } /** * Gets the status whether multi tenant auth is disabled or not. * @return the flag indicating if multi tenant is disabled or not. */ public boolean isMultiTenantAuthenticationDisabled() { return multiTenantAuthDisabled; } /** * Disable the multi tenant authentication. * @return the updated identity client options */ public IdentityClientOptions disableMultiTenantAuthentication() { this.multiTenantAuthDisabled = true; return this; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiguration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Get the configured Identity Log options. * @return the identity log options. */ public IdentityLogOptionsImpl getIdentityLogOptionsImpl() { return identityLogOptionsImpl; } /** * Set the Identity Log options. * @return the identity log options. */ public IdentityClientOptions setIdentityLogOptionsImpl(IdentityLogOptionsImpl identityLogOptionsImpl) { this.identityLogOptionsImpl = identityLogOptionsImpl; return this; } /** * Set the Managed Identity Type * @param managedIdentityType the Managed Identity Type * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityType(ManagedIdentityType managedIdentityType) { this.managedIdentityType = managedIdentityType; return this; } /** * Get the Managed Identity Type * @return the Managed Identity Type */ public ManagedIdentityType getManagedIdentityType() { return managedIdentityType; } /** * Get the Managed Identity parameters * @return the Managed Identity Parameters */ public ManagedIdentityParameters getManagedIdentityParameters() { return managedIdentityParameters; } /** * Configure the managed identity parameters. * * @param managedIdentityParameters the managed identity parameters to use for authentication. * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityParameters(ManagedIdentityParameters managedIdentityParameters) { this.managedIdentityParameters = managedIdentityParameters; return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed Tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public IdentityClientOptions setAdditionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); return this; } /** * Get the Additionally Allowed Tenants. * @return the List containing additionally allowed tenants. */ public Set<String> getAdditionallyAllowedTenants() { return this.additionallyAllowedTenants; } /** * Configure the client options. * @param clientOptions the client options input. * @return the updated client options */ public IdentityClientOptions setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Get the configured client options. * @return the client options. */ public ClientOptions getClientOptions() { return this.clientOptions; } /** * Configure the client options. * @param httpLogOptions the Http log options input. * @return the updated client options */ public IdentityClientOptions setHttpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Get the configured Http log options. * @return the Http log options. */ public HttpLogOptions getHttpLogOptions() { return this.httpLogOptions; } /** * Configure the retry options. * @param retryOptions the retry options input. * @return the updated client options */ public IdentityClientOptions setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Get the configured retry options. * @return the retry options. */ public RetryOptions getRetryOptions() { return this.retryOptions; } /** * Configure the retry policy. * @param retryPolicy the retry policy. * @return the updated client options */ public IdentityClientOptions setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Get the configured retry policy. * @return the retry policy. */ public RetryPolicy getRetryPolicy() { return this.retryPolicy; } /** * Add a per call policy. * @param httpPipelinePolicy the http pipeline policy to add. * @return the updated client options */ public IdentityClientOptions addPerCallPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perCallPolicies.add(httpPipelinePolicy); return this; } /** * Add a per retry policy. * @param httpPipelinePolicy the retry policy to be added. * @return the updated client options */ public IdentityClientOptions addPerRetryPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perRetryPolicies.add(httpPipelinePolicy); return this; } /** * Get the configured per retry policies. * @return the per retry policies. */ public List<HttpPipelinePolicy> getPerRetryPolicies() { return this.perRetryPolicies; } /** * Get the configured per call policies. * @return the per call policies. */ public List<HttpPipelinePolicy> getPerCallPolicies() { return this.perCallPolicies; } IdentityClientOptions setCp1Disabled(boolean cp1Disabled) { this.cp1Disabled = cp1Disabled; return this; } IdentityClientOptions setMultiTenantAuthDisabled(boolean multiTenantAuthDisabled) { this.multiTenantAuthDisabled = multiTenantAuthDisabled; return this; } IdentityClientOptions setAdditionallyAllowedTenants(Set<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = additionallyAllowedTenants; return this; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } IdentityClientOptions setConfigurationStore(Configuration configuration) { this.configuration = configuration; return this; } IdentityClientOptions setUserAssertion(UserAssertion userAssertion) { this.userAssertion = userAssertion; return this; } IdentityClientOptions setPersistenceCache(boolean persistenceCache) { this.sharedTokenCacheEnabled = persistenceCache; return this; } IdentityClientOptions setImdsAuthorityHost(String imdsAuthorityHost) { this.imdsAuthorityHost = imdsAuthorityHost; return this; } IdentityClientOptions setPerCallPolicies(List<HttpPipelinePolicy> perCallPolicies) { this.perCallPolicies = perCallPolicies; return this; } IdentityClientOptions setPerRetryPolicies(List<HttpPipelinePolicy> perRetryPolicies) { this.perRetryPolicies = perRetryPolicies; return this; } /** * Disable instance discovery. Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return the updated client options */ public IdentityClientOptions disableInstanceDisovery() { this.instanceDiscovery = false; return this; } /** * Gets the instance discovery policy. * @return boolean indicating if instance discovery is enabled. */ public boolean getInstanceDiscovery() { return this.instanceDiscovery; } /** * Loads the details from the specified Configuration Store. */ private void loadFromConfiguration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); imdsAuthorityHost = configuration.get(AZURE_POD_IDENTITY_AUTHORITY_HOST, IdentityConstants.DEFAULT_IMDS_ENDPOINT); ValidationUtil.validateAuthHost(authorityHost, LOGGER); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); multiTenantAuthDisabled = configuration .get(AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH, false); } /** * Gets the timeout to apply to developer credential operations. * @return The timeout value for developer credential operations. */ public Duration getDeveloperCredentialTimeout() { return developerCredentialTimeout; } /** * Sets the timeout for developer credential operations. * @param developerCredentialTimeout The timeout value for developer credential operations. */ public IdentityClientOptions clone() { IdentityClientOptions clone = new IdentityClientOptions() .setAdditionallyAllowedTenants(this.additionallyAllowedTenants) .setAllowUnencryptedCache(this.allowUnencryptedCache) .setHttpClient(this.httpClient) .setAuthenticationRecord(this.authenticationRecord) .setExecutorService(this.executorService) .setIdentityLogOptionsImpl(this.identityLogOptionsImpl) .setTokenCacheOptions(this.tokenCachePersistenceOptions) .setRetryTimeout(this.retryTimeout) .setRegionalAuthority(this.regionalAuthority) .setHttpPipeline(this.httpPipeline) .setIncludeX5c(this.includeX5c) .setProxyOptions(this.proxyOptions) .setMaxRetry(this.maxRetry) .setIntelliJKeePassDatabasePath(this.keePassDatabasePath) .setAuthorityHost(this.authorityHost) .setImdsAuthorityHost(this.imdsAuthorityHost) .setCp1Disabled(this.cp1Disabled) .setMultiTenantAuthDisabled(this.multiTenantAuthDisabled) .setUserAssertion(this.userAssertion) .setConfigurationStore(this.configuration) .setPersistenceCache(this.sharedTokenCacheEnabled) .setClientOptions(this.clientOptions) .setHttpLogOptions(this.httpLogOptions) .setRetryOptions(this.retryOptions) .setRetryPolicy(this.retryPolicy) .setPerCallPolicies(this.perCallPolicies) .setPerRetryPolicies(this.perRetryPolicies); if (!getInstanceDiscovery()) { clone.disableInstanceDisovery(); } return clone; } }
what if user passes in null or a zero second timeout ? should we enforce a min bar ?
public DefaultAzureCredentialBuilder developerCredentialTimeout(Duration duration) { this.identityClientOptions.setDeveloperCredentialTimeout(duration); return this; }
this.identityClientOptions.setDeveloperCredentialTimeout(duration);
public DefaultAzureCredentialBuilder developerCredentialTimeout(Duration duration) { this.identityClientOptions.setDeveloperCredentialTimeout(duration); return this; }
class DefaultAzureCredentialBuilder extends CredentialBuilderBase<DefaultAzureCredentialBuilder> { private static final ClientLogger LOGGER = new ClientLogger(DefaultAzureCredentialBuilder.class); private String tenantId; private String managedIdentityClientId; private String workloadIdentityClientId; private String managedIdentityResourceId; private List<String> additionallyAllowedTenants = IdentityUtil .getAdditionalTenantsFromEnvironment(Configuration.getGlobalConfiguration().clone()); /** * Creates an instance of a DefaultAzureCredentialBuilder. */ public DefaultAzureCredentialBuilder() { this.identityClientOptions.setIdentityLogOptionsImpl(new IdentityLogOptionsImpl(true)); } /** * Sets the tenant id of the user to authenticate through the {@link DefaultAzureCredential}. If unset, the value * in the AZURE_TENANT_ID environment variable will be used. If neither is set, the default is null * and will authenticate users to their default tenant. * * @param tenantId the tenant ID to set. * @return An updated instance of this builder with the tenant id set as specified. */ public DefaultAzureCredentialBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return An updated instance of this builder with the authority host set as specified. */ public DefaultAzureCredentialBuilder authorityHost(String authorityHost) { this.identityClientOptions.setAuthorityHost(authorityHost); return this; } /** * Specifies the KeePass database path to read the cached credentials of Azure toolkit for IntelliJ plugin. * The {@code databasePath} is required on Windows platform. For macOS and Linux platform native key chain / * key ring will be accessed respectively to retrieve the cached credentials. * * <p>This path can be located in the IntelliJ IDE. * Windows: File -&gt; Settings -&gt; Appearance &amp; Behavior -&gt; System Settings -&gt; Passwords. </p> * * @param databasePath the path to the KeePass database. * @throws IllegalArgumentException if {@code databasePath} is either not specified or is empty. * @return An updated instance of this builder with the KeePass database path set as specified. */ public DefaultAzureCredentialBuilder intelliJKeePassDatabasePath(String databasePath) { if (CoreUtils.isNullOrEmpty(databasePath)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The KeePass database path is either empty or not configured." + " Please configure it on the builder.")); } this.identityClientOptions.setIntelliJKeePassDatabasePath(databasePath); return this; } /** * Specifies the client ID of user assigned or system assigned identity, when this credential is running * in an environment with managed identities. If unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If neither is set, the default value is null and will only work with system assigned * managed identities and not user assigned managed identities. * * Only one of managedIdentityClientId and managedIdentityResourceId can be specified. * * @param clientId the client ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder managedIdentityClientId(String clientId) { this.managedIdentityClientId = clientId; return this; } /** * Specifies the client ID of Azure AD app to be used for AKS workload identity authentication. * if unset, {@link DefaultAzureCredentialBuilder * If both values are unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If none are set, the default value is null and Workload Identity authentication will not be attempted. * * @param clientId the client ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder workloadIdentityClientId(String clientId) { this.workloadIdentityClientId = clientId; return this; } /** * Specifies the resource ID of user assigned or system assigned identity, when this credential is running * in an environment with managed identities. If unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If neither is set, the default value is null and will only work with system assigned * managed identities and not user assigned managed identities. * * Only one of managedIdentityResourceId and managedIdentityClientId can be specified. * * @param resourceId the resource ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder managedIdentityResourceId(String resourceId) { this.managedIdentityResourceId = resourceId; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return An updated instance of this builder with the executor service set as specified. */ public DefaultAzureCredentialBuilder executorService(ExecutorService executorService) { this.identityClientOptions.setExecutorService(executorService); return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public DefaultAzureCredentialBuilder additionallyAllowedTenants(String... additionallyAllowedTenants) { this.additionallyAllowedTenants = IdentityUtil.resolveAdditionalTenants(Arrays.asList(additionallyAllowedTenants)); return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public DefaultAzureCredentialBuilder additionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = IdentityUtil.resolveAdditionalTenants(additionallyAllowedTenants); return this; } /** * Specifies a {@link Duration} timeout for developer credentials (such as Azure CLI or IntelliJ). * @param duration The {@link Duration} to wait. * @return An updated instance of this builder with the timeout specified. */ /** * Creates new {@link DefaultAzureCredential} with the configured options set. * * @return a {@link DefaultAzureCredential} with the current configurations. * @throws IllegalStateException if clientId and resourceId are both set. */ public DefaultAzureCredential build() { loadFallbackValuesFromEnvironment(); if (managedIdentityClientId != null && managedIdentityResourceId != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Only one of managedIdentityResourceId and managedIdentityClientId can be specified.")); } if (!CoreUtils.isNullOrEmpty(additionallyAllowedTenants)) { identityClientOptions.setAdditionallyAllowedTenants(additionallyAllowedTenants); } return new DefaultAzureCredential(getCredentialsChain()); } private void loadFallbackValuesFromEnvironment() { Configuration configuration = identityClientOptions.getConfiguration() == null ? Configuration.getGlobalConfiguration().clone() : identityClientOptions.getConfiguration(); tenantId = CoreUtils.isNullOrEmpty(tenantId) ? configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID) : tenantId; managedIdentityClientId = CoreUtils.isNullOrEmpty(managedIdentityClientId) ? configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID) : managedIdentityClientId; } private ArrayList<TokenCredential> getCredentialsChain() { WorkloadIdentityCredential workloadIdentityCredential = getWorkloadIdentityCredentialIfAvailable(); ArrayList<TokenCredential> output = new ArrayList<TokenCredential>(workloadIdentityCredential != null ? 8 : 7); output.add(new EnvironmentCredential(identityClientOptions.clone())); if (workloadIdentityCredential != null) { output.add(workloadIdentityCredential); } output.add(new ManagedIdentityCredential(managedIdentityClientId, managedIdentityResourceId, identityClientOptions.clone())); output.add(new AzureDeveloperCliCredential(tenantId, identityClientOptions.clone())); output.add(new SharedTokenCacheCredential(null, IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID, tenantId, identityClientOptions.clone())); output.add(new IntelliJCredential(tenantId, identityClientOptions.clone())); output.add(new AzureCliCredential(tenantId, identityClientOptions.clone())); output.add(new AzurePowerShellCredential(tenantId, identityClientOptions.clone())); return output; } private WorkloadIdentityCredential getWorkloadIdentityCredentialIfAvailable() { Configuration configuration = identityClientOptions.getConfiguration() == null ? Configuration.getGlobalConfiguration().clone() : identityClientOptions.getConfiguration(); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String federatedTokenFilePath = configuration.get(AZURE_FEDERATED_TOKEN_FILE); String azureAuthorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST); String clientId = CoreUtils.isNullOrEmpty(workloadIdentityClientId) ? managedIdentityClientId : workloadIdentityClientId; if (!(CoreUtils.isNullOrEmpty(tenantId) || CoreUtils.isNullOrEmpty(federatedTokenFilePath) || CoreUtils.isNullOrEmpty(clientId) || CoreUtils.isNullOrEmpty(azureAuthorityHost))) { return new WorkloadIdentityCredential(tenantId, clientId, federatedTokenFilePath, identityClientOptions.setAuthorityHost(azureAuthorityHost).clone()); } return null; } }
class DefaultAzureCredentialBuilder extends CredentialBuilderBase<DefaultAzureCredentialBuilder> { private static final ClientLogger LOGGER = new ClientLogger(DefaultAzureCredentialBuilder.class); private String tenantId; private String managedIdentityClientId; private String workloadIdentityClientId; private String managedIdentityResourceId; private List<String> additionallyAllowedTenants = IdentityUtil .getAdditionalTenantsFromEnvironment(Configuration.getGlobalConfiguration().clone()); /** * Creates an instance of a DefaultAzureCredentialBuilder. */ public DefaultAzureCredentialBuilder() { this.identityClientOptions.setIdentityLogOptionsImpl(new IdentityLogOptionsImpl(true)); } /** * Sets the tenant id of the user to authenticate through the {@link DefaultAzureCredential}. If unset, the value * in the AZURE_TENANT_ID environment variable will be used. If neither is set, the default is null * and will authenticate users to their default tenant. * * @param tenantId the tenant ID to set. * @return An updated instance of this builder with the tenant id set as specified. */ public DefaultAzureCredentialBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return An updated instance of this builder with the authority host set as specified. */ public DefaultAzureCredentialBuilder authorityHost(String authorityHost) { this.identityClientOptions.setAuthorityHost(authorityHost); return this; } /** * Specifies the KeePass database path to read the cached credentials of Azure toolkit for IntelliJ plugin. * The {@code databasePath} is required on Windows platform. For macOS and Linux platform native key chain / * key ring will be accessed respectively to retrieve the cached credentials. * * <p>This path can be located in the IntelliJ IDE. * Windows: File -&gt; Settings -&gt; Appearance &amp; Behavior -&gt; System Settings -&gt; Passwords. </p> * * @param databasePath the path to the KeePass database. * @throws IllegalArgumentException if {@code databasePath} is either not specified or is empty. * @return An updated instance of this builder with the KeePass database path set as specified. */ public DefaultAzureCredentialBuilder intelliJKeePassDatabasePath(String databasePath) { if (CoreUtils.isNullOrEmpty(databasePath)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The KeePass database path is either empty or not configured." + " Please configure it on the builder.")); } this.identityClientOptions.setIntelliJKeePassDatabasePath(databasePath); return this; } /** * Specifies the client ID of user assigned or system assigned identity, when this credential is running * in an environment with managed identities. If unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If neither is set, the default value is null and will only work with system assigned * managed identities and not user assigned managed identities. * * Only one of managedIdentityClientId and managedIdentityResourceId can be specified. * * @param clientId the client ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder managedIdentityClientId(String clientId) { this.managedIdentityClientId = clientId; return this; } /** * Specifies the client ID of Azure AD app to be used for AKS workload identity authentication. * if unset, {@link DefaultAzureCredentialBuilder * If both values are unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If none are set, the default value is null and Workload Identity authentication will not be attempted. * * @param clientId the client ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder workloadIdentityClientId(String clientId) { this.workloadIdentityClientId = clientId; return this; } /** * Specifies the resource ID of user assigned or system assigned identity, when this credential is running * in an environment with managed identities. If unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If neither is set, the default value is null and will only work with system assigned * managed identities and not user assigned managed identities. * * Only one of managedIdentityResourceId and managedIdentityClientId can be specified. * * @param resourceId the resource ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder managedIdentityResourceId(String resourceId) { this.managedIdentityResourceId = resourceId; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return An updated instance of this builder with the executor service set as specified. */ public DefaultAzureCredentialBuilder executorService(ExecutorService executorService) { this.identityClientOptions.setExecutorService(executorService); return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public DefaultAzureCredentialBuilder additionallyAllowedTenants(String... additionallyAllowedTenants) { this.additionallyAllowedTenants = IdentityUtil.resolveAdditionalTenants(Arrays.asList(additionallyAllowedTenants)); return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public DefaultAzureCredentialBuilder additionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = IdentityUtil.resolveAdditionalTenants(additionallyAllowedTenants); return this; } /** * Specifies a {@link Duration} timeout for developer credentials (such as Azure CLI or IntelliJ). * @param duration The {@link Duration} to wait. * @return An updated instance of this builder with the timeout specified. */ /** * Disable instance discovery. Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return An updated instance of this builder with instance discovery disabled. */ public DefaultAzureCredentialBuilder disableInstanceDiscovery() { this.identityClientOptions.disableInstanceDisovery(); return this; } /** * Creates new {@link DefaultAzureCredential} with the configured options set. * * @return a {@link DefaultAzureCredential} with the current configurations. * @throws IllegalStateException if clientId and resourceId are both set. */ public DefaultAzureCredential build() { loadFallbackValuesFromEnvironment(); if (managedIdentityClientId != null && managedIdentityResourceId != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Only one of managedIdentityResourceId and managedIdentityClientId can be specified.")); } if (!CoreUtils.isNullOrEmpty(additionallyAllowedTenants)) { identityClientOptions.setAdditionallyAllowedTenants(additionallyAllowedTenants); } return new DefaultAzureCredential(getCredentialsChain()); } private void loadFallbackValuesFromEnvironment() { Configuration configuration = identityClientOptions.getConfiguration() == null ? Configuration.getGlobalConfiguration().clone() : identityClientOptions.getConfiguration(); tenantId = CoreUtils.isNullOrEmpty(tenantId) ? configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID) : tenantId; managedIdentityClientId = CoreUtils.isNullOrEmpty(managedIdentityClientId) ? configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID) : managedIdentityClientId; } private ArrayList<TokenCredential> getCredentialsChain() { WorkloadIdentityCredential workloadIdentityCredential = getWorkloadIdentityCredentialIfAvailable(); ArrayList<TokenCredential> output = new ArrayList<TokenCredential>(workloadIdentityCredential != null ? 8 : 7); output.add(new EnvironmentCredential(identityClientOptions.clone())); if (workloadIdentityCredential != null) { output.add(workloadIdentityCredential); } output.add(new ManagedIdentityCredential(managedIdentityClientId, managedIdentityResourceId, identityClientOptions.clone())); output.add(new AzureDeveloperCliCredential(tenantId, identityClientOptions.clone())); output.add(new SharedTokenCacheCredential(null, IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID, tenantId, identityClientOptions.clone())); output.add(new IntelliJCredential(tenantId, identityClientOptions.clone())); output.add(new AzureCliCredential(tenantId, identityClientOptions.clone())); output.add(new AzurePowerShellCredential(tenantId, identityClientOptions.clone())); return output; } private WorkloadIdentityCredential getWorkloadIdentityCredentialIfAvailable() { Configuration configuration = identityClientOptions.getConfiguration() == null ? Configuration.getGlobalConfiguration().clone() : identityClientOptions.getConfiguration(); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String federatedTokenFilePath = configuration.get(AZURE_FEDERATED_TOKEN_FILE); String azureAuthorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST); String clientId = CoreUtils.isNullOrEmpty(workloadIdentityClientId) ? managedIdentityClientId : workloadIdentityClientId; if (!(CoreUtils.isNullOrEmpty(tenantId) || CoreUtils.isNullOrEmpty(federatedTokenFilePath) || CoreUtils.isNullOrEmpty(clientId) || CoreUtils.isNullOrEmpty(azureAuthorityHost))) { return new WorkloadIdentityCredential(tenantId, clientId, federatedTokenFilePath, identityClientOptions.setAuthorityHost(azureAuthorityHost).clone()); } return null; } }
I think it's tricky to do that given the range of computers that exist. I also think users are unlikely to do something like that and they'll catch it pretty quickly.
public void setDeveloperCredentialTimeout(Duration developerCredentialTimeout) { this.developerCredentialTimeout = developerCredentialTimeout; }
this.developerCredentialTimeout = developerCredentialTimeout;
public void setDeveloperCredentialTimeout(Duration developerCredentialTimeout) { this.developerCredentialTimeout = developerCredentialTimeout; }
class IdentityClientOptions implements Cloneable { private static final ClientLogger LOGGER = new ClientLogger(IdentityClientOptions.class); private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"; public static final String AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"; private String authorityHost; private String imdsAuthorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private UserAssertion userAssertion; private boolean multiTenantAuthDisabled; private Configuration configuration; private IdentityLogOptionsImpl identityLogOptionsImpl; private boolean accountIdentifierLogging; private ManagedIdentityType managedIdentityType; private ManagedIdentityParameters managedIdentityParameters; private Set<String> additionallyAllowedTenants; private ClientOptions clientOptions; private HttpLogOptions httpLogOptions; private RetryOptions retryOptions; private RetryPolicy retryPolicy; private List<HttpPipelinePolicy> perCallPolicies; private List<HttpPipelinePolicy> perRetryPolicies; private boolean instanceDiscovery; private Duration developerCredentialTimeout = Duration.ofSeconds(10); /** * Creates an instance of IdentityClientOptions with default settings. */ public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration().clone(); loadFromConfiguration(configuration); identityLogOptionsImpl = new IdentityLogOptionsImpl(); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); additionallyAllowedTenants = new HashSet<>(); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); instanceDiscovery = true; } /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the AKS Pod Authority endpoint to acquire tokens. */ public String getImdsAuthorityHost() { return imdsAuthorityHost; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Configure the User Assertion Scope to be used for OnBehalfOf Authentication request. * * @param userAssertion the user assertion access token to be used for On behalf Of authentication flow * @return the updated identity client options */ public IdentityClientOptions userAssertion(String userAssertion) { this.userAssertion = new UserAssertion(userAssertion); return this; } /** * Get the configured {@link UserAssertion} * * @return the configured user assertion scope */ public UserAssertion getUserAssertion() { return this.userAssertion; } /** * Gets the status whether multi tenant auth is disabled or not. * @return the flag indicating if multi tenant is disabled or not. */ public boolean isMultiTenantAuthenticationDisabled() { return multiTenantAuthDisabled; } /** * Disable the multi tenant authentication. * @return the updated identity client options */ public IdentityClientOptions disableMultiTenantAuthentication() { this.multiTenantAuthDisabled = true; return this; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiguration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Get the configured Identity Log options. * @return the identity log options. */ public IdentityLogOptionsImpl getIdentityLogOptionsImpl() { return identityLogOptionsImpl; } /** * Set the Identity Log options. * @return the identity log options. */ public IdentityClientOptions setIdentityLogOptionsImpl(IdentityLogOptionsImpl identityLogOptionsImpl) { this.identityLogOptionsImpl = identityLogOptionsImpl; return this; } /** * Set the Managed Identity Type * @param managedIdentityType the Managed Identity Type * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityType(ManagedIdentityType managedIdentityType) { this.managedIdentityType = managedIdentityType; return this; } /** * Get the Managed Identity Type * @return the Managed Identity Type */ public ManagedIdentityType getManagedIdentityType() { return managedIdentityType; } /** * Get the Managed Identity parameters * @return the Managed Identity Parameters */ public ManagedIdentityParameters getManagedIdentityParameters() { return managedIdentityParameters; } /** * Configure the managed identity parameters. * * @param managedIdentityParameters the managed identity parameters to use for authentication. * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityParameters(ManagedIdentityParameters managedIdentityParameters) { this.managedIdentityParameters = managedIdentityParameters; return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed Tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public IdentityClientOptions setAdditionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); return this; } /** * Get the Additionally Allowed Tenants. * @return the List containing additionally allowed tenants. */ public Set<String> getAdditionallyAllowedTenants() { return this.additionallyAllowedTenants; } /** * Configure the client options. * @param clientOptions the client options input. * @return the updated client options */ public IdentityClientOptions setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Get the configured client options. * @return the client options. */ public ClientOptions getClientOptions() { return this.clientOptions; } /** * Configure the client options. * @param httpLogOptions the Http log options input. * @return the updated client options */ public IdentityClientOptions setHttpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Get the configured Http log options. * @return the Http log options. */ public HttpLogOptions getHttpLogOptions() { return this.httpLogOptions; } /** * Configure the retry options. * @param retryOptions the retry options input. * @return the updated client options */ public IdentityClientOptions setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Get the configured retry options. * @return the retry options. */ public RetryOptions getRetryOptions() { return this.retryOptions; } /** * Configure the retry policy. * @param retryPolicy the retry policy. * @return the updated client options */ public IdentityClientOptions setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Get the configured retry policy. * @return the retry policy. */ public RetryPolicy getRetryPolicy() { return this.retryPolicy; } /** * Add a per call policy. * @param httpPipelinePolicy the http pipeline policy to add. * @return the updated client options */ public IdentityClientOptions addPerCallPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perCallPolicies.add(httpPipelinePolicy); return this; } /** * Add a per retry policy. * @param httpPipelinePolicy the retry policy to be added. * @return the updated client options */ public IdentityClientOptions addPerRetryPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perRetryPolicies.add(httpPipelinePolicy); return this; } /** * Get the configured per retry policies. * @return the per retry policies. */ public List<HttpPipelinePolicy> getPerRetryPolicies() { return this.perRetryPolicies; } /** * Get the configured per call policies. * @return the per call policies. */ public List<HttpPipelinePolicy> getPerCallPolicies() { return this.perCallPolicies; } IdentityClientOptions setCp1Disabled(boolean cp1Disabled) { this.cp1Disabled = cp1Disabled; return this; } IdentityClientOptions setMultiTenantAuthDisabled(boolean multiTenantAuthDisabled) { this.multiTenantAuthDisabled = multiTenantAuthDisabled; return this; } IdentityClientOptions setAdditionallyAllowedTenants(Set<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = additionallyAllowedTenants; return this; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } IdentityClientOptions setConfigurationStore(Configuration configuration) { this.configuration = configuration; return this; } IdentityClientOptions setUserAssertion(UserAssertion userAssertion) { this.userAssertion = userAssertion; return this; } IdentityClientOptions setPersistenceCache(boolean persistenceCache) { this.sharedTokenCacheEnabled = persistenceCache; return this; } IdentityClientOptions setImdsAuthorityHost(String imdsAuthorityHost) { this.imdsAuthorityHost = imdsAuthorityHost; return this; } IdentityClientOptions setPerCallPolicies(List<HttpPipelinePolicy> perCallPolicies) { this.perCallPolicies = perCallPolicies; return this; } IdentityClientOptions setPerRetryPolicies(List<HttpPipelinePolicy> perRetryPolicies) { this.perRetryPolicies = perRetryPolicies; return this; } /** * Disable instance discovery. Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return the updated client options */ public IdentityClientOptions disableInstanceDisovery() { this.instanceDiscovery = false; return this; } /** * Gets the instance discovery policy. * @return boolean indicating if instance discovery is enabled. */ public boolean getInstanceDiscovery() { return this.instanceDiscovery; } /** * Loads the details from the specified Configuration Store. */ private void loadFromConfiguration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); imdsAuthorityHost = configuration.get(AZURE_POD_IDENTITY_AUTHORITY_HOST, IdentityConstants.DEFAULT_IMDS_ENDPOINT); ValidationUtil.validateAuthHost(authorityHost, LOGGER); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); multiTenantAuthDisabled = configuration .get(AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH, false); } /** * Gets the timeout to apply to developer credential operations. * @return The timeout value for developer credential operations. */ public Duration getDeveloperCredentialTimeout() { return developerCredentialTimeout; } /** * Sets the timeout for developer credential operations. * @param developerCredentialTimeout The timeout value for developer credential operations. */ public IdentityClientOptions clone() { IdentityClientOptions clone = new IdentityClientOptions() .setAdditionallyAllowedTenants(this.additionallyAllowedTenants) .setAllowUnencryptedCache(this.allowUnencryptedCache) .setHttpClient(this.httpClient) .setAuthenticationRecord(this.authenticationRecord) .setExecutorService(this.executorService) .setIdentityLogOptionsImpl(this.identityLogOptionsImpl) .setTokenCacheOptions(this.tokenCachePersistenceOptions) .setRetryTimeout(this.retryTimeout) .setRegionalAuthority(this.regionalAuthority) .setHttpPipeline(this.httpPipeline) .setIncludeX5c(this.includeX5c) .setProxyOptions(this.proxyOptions) .setMaxRetry(this.maxRetry) .setIntelliJKeePassDatabasePath(this.keePassDatabasePath) .setAuthorityHost(this.authorityHost) .setImdsAuthorityHost(this.imdsAuthorityHost) .setCp1Disabled(this.cp1Disabled) .setMultiTenantAuthDisabled(this.multiTenantAuthDisabled) .setUserAssertion(this.userAssertion) .setConfigurationStore(this.configuration) .setPersistenceCache(this.sharedTokenCacheEnabled) .setClientOptions(this.clientOptions) .setHttpLogOptions(this.httpLogOptions) .setRetryOptions(this.retryOptions) .setRetryPolicy(this.retryPolicy) .setPerCallPolicies(this.perCallPolicies) .setPerRetryPolicies(this.perRetryPolicies); if (!getInstanceDiscovery()) { clone.disableInstanceDisovery(); } return clone; } }
class IdentityClientOptions implements Cloneable { private static final ClientLogger LOGGER = new ClientLogger(IdentityClientOptions.class); private static final int MAX_RETRY_DEFAULT_LIMIT = 3; public static final String AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"; public static final String AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"; private String authorityHost; private String imdsAuthorityHost; private int maxRetry; private Function<Duration, Duration> retryTimeout; private ProxyOptions proxyOptions; private HttpPipeline httpPipeline; private ExecutorService executorService; private HttpClient httpClient; private boolean allowUnencryptedCache; private boolean sharedTokenCacheEnabled; private String keePassDatabasePath; private boolean includeX5c; private AuthenticationRecord authenticationRecord; private TokenCachePersistenceOptions tokenCachePersistenceOptions; private boolean cp1Disabled; private RegionalAuthority regionalAuthority; private UserAssertion userAssertion; private boolean multiTenantAuthDisabled; private Configuration configuration; private IdentityLogOptionsImpl identityLogOptionsImpl; private boolean accountIdentifierLogging; private ManagedIdentityType managedIdentityType; private ManagedIdentityParameters managedIdentityParameters; private Set<String> additionallyAllowedTenants; private ClientOptions clientOptions; private HttpLogOptions httpLogOptions; private RetryOptions retryOptions; private RetryPolicy retryPolicy; private List<HttpPipelinePolicy> perCallPolicies; private List<HttpPipelinePolicy> perRetryPolicies; private boolean instanceDiscovery; private Duration developerCredentialTimeout = Duration.ofSeconds(10); /** * Creates an instance of IdentityClientOptions with default settings. */ public IdentityClientOptions() { Configuration configuration = Configuration.getGlobalConfiguration().clone(); loadFromConfiguration(configuration); identityLogOptionsImpl = new IdentityLogOptionsImpl(); maxRetry = MAX_RETRY_DEFAULT_LIMIT; retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSeconds() - 1)); perCallPolicies = new ArrayList<>(); perRetryPolicies = new ArrayList<>(); additionallyAllowedTenants = new HashSet<>(); regionalAuthority = RegionalAuthority.fromString( configuration.get(Configuration.PROPERTY_AZURE_REGIONAL_AUTHORITY_NAME)); instanceDiscovery = true; } /** * @return the Azure Active Directory endpoint to acquire tokens. */ public String getAuthorityHost() { return authorityHost; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return IdentityClientOptions */ public IdentityClientOptions setAuthorityHost(String authorityHost) { this.authorityHost = authorityHost; return this; } /** * @return the AKS Pod Authority endpoint to acquire tokens. */ public String getImdsAuthorityHost() { return imdsAuthorityHost; } /** * @return the max number of retries when an authentication request fails. */ public int getMaxRetry() { return maxRetry; } /** * Specifies the max number of retries when an authentication request fails. * @param maxRetry the number of retries * @return IdentityClientOptions */ public IdentityClientOptions setMaxRetry(int maxRetry) { this.maxRetry = maxRetry; return this; } /** * @return a Function to calculate seconds of timeout on every retried request. */ public Function<Duration, Duration> getRetryTimeout() { return retryTimeout; } /** * Specifies a Function to calculate seconds of timeout on every retried request. * @param retryTimeout the Function that returns a timeout in seconds given the number of retry * @return IdentityClientOptions */ public IdentityClientOptions setRetryTimeout(Function<Duration, Duration> retryTimeout) { this.retryTimeout = retryTimeout; return this; } /** * @return the options for proxy configuration. */ public ProxyOptions getProxyOptions() { return proxyOptions; } /** * Specifies the options for proxy configuration. * @param proxyOptions the options for proxy configuration * @return IdentityClientOptions */ public IdentityClientOptions setProxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * @return the HttpPipeline to send all requests */ public HttpPipeline getHttpPipeline() { return httpPipeline; } /** * @return the HttpClient to use for requests */ public HttpClient getHttpClient() { return httpClient; } /** * Specifies the HttpPipeline to send all requests. This setting overrides the others. * @param httpPipeline the HttpPipeline to send all requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpPipeline(HttpPipeline httpPipeline) { this.httpPipeline = httpPipeline; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return IdentityClientOptions */ public IdentityClientOptions setExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } /** * @return the ExecutorService to execute authentication requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Specifies the HttpClient to send use for requests. * @param httpClient the http client to use for requests * @return IdentityClientOptions */ public IdentityClientOptions setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @param allowUnencryptedCache the flag to indicate if unencrypted persistent cache is allowed for use or not. * @return The updated identity client options. */ public IdentityClientOptions setAllowUnencryptedCache(boolean allowUnencryptedCache) { this.allowUnencryptedCache = allowUnencryptedCache; return this; } public boolean getAllowUnencryptedCache() { return this.allowUnencryptedCache; } /** * Specifies the database to extract IntelliJ cached credentials from. * @param keePassDatabasePath the database to extract intellij credentials from. * @return IdentityClientOptions */ public IdentityClientOptions setIntelliJKeePassDatabasePath(String keePassDatabasePath) { this.keePassDatabasePath = keePassDatabasePath; return this; } /** * Gets if the shared token cache is disabled. * @return if the shared token cache is disabled. */ public boolean isSharedTokenCacheEnabled() { return this.sharedTokenCacheEnabled; } /** * Enables the shared token cache which is disabled by default. If enabled, the client will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return The updated identity client options. */ public IdentityClientOptions enablePersistentCache() { this.sharedTokenCacheEnabled = true; return this; } /* * Get the KeePass database path. * @return the KeePass database path to extract inellij credentials from. */ public String getIntelliJKeePassDatabasePath() { return keePassDatabasePath; } /** * Sets the {@link AuthenticationRecord} captured from a previous authentication. * * @param authenticationRecord The Authentication record to be configured. * * @return An updated instance of this builder with the configured authentication record. */ public IdentityClientOptions setAuthenticationRecord(AuthenticationRecord authenticationRecord) { this.authenticationRecord = authenticationRecord; return this; } /** * Get the status whether x5c claim (public key of the certificate) should be included as part of the authentication * request or not. * @return the status of x5c claim inclusion. */ public boolean isIncludeX5c() { return includeX5c; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request. * The default value is false. * * @param includeX5c true if the x5c should be sent. Otherwise false * @return The updated identity client options. */ public IdentityClientOptions setIncludeX5c(boolean includeX5c) { this.includeX5c = includeX5c; return this; } /** * Get the configured {@link AuthenticationRecord}. * * @return {@link AuthenticationRecord}. */ public AuthenticationRecord getAuthenticationRecord() { return authenticationRecord; } /** * Specifies the {@link TokenCachePersistenceOptions} to be used for token cache persistence. * * @param tokenCachePersistenceOptions the options configuration * @return the updated identity client options */ public IdentityClientOptions setTokenCacheOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { this.tokenCachePersistenceOptions = tokenCachePersistenceOptions; return this; } /** * Get the configured {@link TokenCachePersistenceOptions} * * @return the {@link TokenCachePersistenceOptions} */ public TokenCachePersistenceOptions getTokenCacheOptions() { return this.tokenCachePersistenceOptions; } /** * Check whether CP1 client capability should be disabled. * * @return the status indicating if CP1 client capability should be disabled. */ public boolean isCp1Disabled() { return this.cp1Disabled; } /** * Gets the regional authority, or null if regional authority should not be used. * @return the regional authority value if specified */ public RegionalAuthority getRegionalAuthority() { return regionalAuthority; } /** * Configure the User Assertion Scope to be used for OnBehalfOf Authentication request. * * @param userAssertion the user assertion access token to be used for On behalf Of authentication flow * @return the updated identity client options */ public IdentityClientOptions userAssertion(String userAssertion) { this.userAssertion = new UserAssertion(userAssertion); return this; } /** * Get the configured {@link UserAssertion} * * @return the configured user assertion scope */ public UserAssertion getUserAssertion() { return this.userAssertion; } /** * Gets the status whether multi tenant auth is disabled or not. * @return the flag indicating if multi tenant is disabled or not. */ public boolean isMultiTenantAuthenticationDisabled() { return multiTenantAuthDisabled; } /** * Disable the multi tenant authentication. * @return the updated identity client options */ public IdentityClientOptions disableMultiTenantAuthentication() { this.multiTenantAuthDisabled = true; return this; } /** * Sets the specified configuration store. * * @param configuration the configuration store to be used to read env variables and/or system properties. * @return the updated identity client options */ public IdentityClientOptions setConfiguration(Configuration configuration) { this.configuration = configuration; loadFromConfiguration(configuration); return this; } /** * Gets the configured configuration store. * * @return the configured {@link Configuration} store. */ public Configuration getConfiguration() { return this.configuration; } /** * Get the configured Identity Log options. * @return the identity log options. */ public IdentityLogOptionsImpl getIdentityLogOptionsImpl() { return identityLogOptionsImpl; } /** * Set the Identity Log options. * @return the identity log options. */ public IdentityClientOptions setIdentityLogOptionsImpl(IdentityLogOptionsImpl identityLogOptionsImpl) { this.identityLogOptionsImpl = identityLogOptionsImpl; return this; } /** * Set the Managed Identity Type * @param managedIdentityType the Managed Identity Type * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityType(ManagedIdentityType managedIdentityType) { this.managedIdentityType = managedIdentityType; return this; } /** * Get the Managed Identity Type * @return the Managed Identity Type */ public ManagedIdentityType getManagedIdentityType() { return managedIdentityType; } /** * Get the Managed Identity parameters * @return the Managed Identity Parameters */ public ManagedIdentityParameters getManagedIdentityParameters() { return managedIdentityParameters; } /** * Configure the managed identity parameters. * * @param managedIdentityParameters the managed identity parameters to use for authentication. * @return the updated identity client options */ public IdentityClientOptions setManagedIdentityParameters(ManagedIdentityParameters managedIdentityParameters) { this.managedIdentityParameters = managedIdentityParameters; return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed Tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public IdentityClientOptions setAdditionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); this.additionallyAllowedTenants.addAll(additionallyAllowedTenants); return this; } /** * Get the Additionally Allowed Tenants. * @return the List containing additionally allowed tenants. */ public Set<String> getAdditionallyAllowedTenants() { return this.additionallyAllowedTenants; } /** * Configure the client options. * @param clientOptions the client options input. * @return the updated client options */ public IdentityClientOptions setClientOptions(ClientOptions clientOptions) { this.clientOptions = clientOptions; return this; } /** * Get the configured client options. * @return the client options. */ public ClientOptions getClientOptions() { return this.clientOptions; } /** * Configure the client options. * @param httpLogOptions the Http log options input. * @return the updated client options */ public IdentityClientOptions setHttpLogOptions(HttpLogOptions httpLogOptions) { this.httpLogOptions = httpLogOptions; return this; } /** * Get the configured Http log options. * @return the Http log options. */ public HttpLogOptions getHttpLogOptions() { return this.httpLogOptions; } /** * Configure the retry options. * @param retryOptions the retry options input. * @return the updated client options */ public IdentityClientOptions setRetryOptions(RetryOptions retryOptions) { this.retryOptions = retryOptions; return this; } /** * Get the configured retry options. * @return the retry options. */ public RetryOptions getRetryOptions() { return this.retryOptions; } /** * Configure the retry policy. * @param retryPolicy the retry policy. * @return the updated client options */ public IdentityClientOptions setRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } /** * Get the configured retry policy. * @return the retry policy. */ public RetryPolicy getRetryPolicy() { return this.retryPolicy; } /** * Add a per call policy. * @param httpPipelinePolicy the http pipeline policy to add. * @return the updated client options */ public IdentityClientOptions addPerCallPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perCallPolicies.add(httpPipelinePolicy); return this; } /** * Add a per retry policy. * @param httpPipelinePolicy the retry policy to be added. * @return the updated client options */ public IdentityClientOptions addPerRetryPolicy(HttpPipelinePolicy httpPipelinePolicy) { this.perRetryPolicies.add(httpPipelinePolicy); return this; } /** * Get the configured per retry policies. * @return the per retry policies. */ public List<HttpPipelinePolicy> getPerRetryPolicies() { return this.perRetryPolicies; } /** * Get the configured per call policies. * @return the per call policies. */ public List<HttpPipelinePolicy> getPerCallPolicies() { return this.perCallPolicies; } IdentityClientOptions setCp1Disabled(boolean cp1Disabled) { this.cp1Disabled = cp1Disabled; return this; } IdentityClientOptions setMultiTenantAuthDisabled(boolean multiTenantAuthDisabled) { this.multiTenantAuthDisabled = multiTenantAuthDisabled; return this; } IdentityClientOptions setAdditionallyAllowedTenants(Set<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = additionallyAllowedTenants; return this; } /** * Specifies either the specific regional authority, or use {@link RegionalAuthority * * @param regionalAuthority the regional authority * @return the updated identity client options */ IdentityClientOptions setRegionalAuthority(RegionalAuthority regionalAuthority) { this.regionalAuthority = regionalAuthority; return this; } IdentityClientOptions setConfigurationStore(Configuration configuration) { this.configuration = configuration; return this; } IdentityClientOptions setUserAssertion(UserAssertion userAssertion) { this.userAssertion = userAssertion; return this; } IdentityClientOptions setPersistenceCache(boolean persistenceCache) { this.sharedTokenCacheEnabled = persistenceCache; return this; } IdentityClientOptions setImdsAuthorityHost(String imdsAuthorityHost) { this.imdsAuthorityHost = imdsAuthorityHost; return this; } IdentityClientOptions setPerCallPolicies(List<HttpPipelinePolicy> perCallPolicies) { this.perCallPolicies = perCallPolicies; return this; } IdentityClientOptions setPerRetryPolicies(List<HttpPipelinePolicy> perRetryPolicies) { this.perRetryPolicies = perRetryPolicies; return this; } /** * Disable instance discovery. Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return the updated client options */ public IdentityClientOptions disableInstanceDisovery() { this.instanceDiscovery = false; return this; } /** * Gets the instance discovery policy. * @return boolean indicating if instance discovery is enabled. */ public boolean getInstanceDiscovery() { return this.instanceDiscovery; } /** * Loads the details from the specified Configuration Store. */ private void loadFromConfiguration(Configuration configuration) { authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD); imdsAuthorityHost = configuration.get(AZURE_POD_IDENTITY_AUTHORITY_HOST, IdentityConstants.DEFAULT_IMDS_ENDPOINT); ValidationUtil.validateAuthHost(authorityHost, LOGGER); cp1Disabled = configuration.get(Configuration.PROPERTY_AZURE_IDENTITY_DISABLE_CP1, false); multiTenantAuthDisabled = configuration .get(AZURE_IDENTITY_DISABLE_MULTI_TENANT_AUTH, false); } /** * Gets the timeout to apply to developer credential operations. * @return The timeout value for developer credential operations. */ public Duration getDeveloperCredentialTimeout() { return developerCredentialTimeout; } /** * Sets the timeout for developer credential operations. * @param developerCredentialTimeout The timeout value for developer credential operations. */ public IdentityClientOptions clone() { IdentityClientOptions clone = new IdentityClientOptions() .setAdditionallyAllowedTenants(this.additionallyAllowedTenants) .setAllowUnencryptedCache(this.allowUnencryptedCache) .setHttpClient(this.httpClient) .setAuthenticationRecord(this.authenticationRecord) .setExecutorService(this.executorService) .setIdentityLogOptionsImpl(this.identityLogOptionsImpl) .setTokenCacheOptions(this.tokenCachePersistenceOptions) .setRetryTimeout(this.retryTimeout) .setRegionalAuthority(this.regionalAuthority) .setHttpPipeline(this.httpPipeline) .setIncludeX5c(this.includeX5c) .setProxyOptions(this.proxyOptions) .setMaxRetry(this.maxRetry) .setIntelliJKeePassDatabasePath(this.keePassDatabasePath) .setAuthorityHost(this.authorityHost) .setImdsAuthorityHost(this.imdsAuthorityHost) .setCp1Disabled(this.cp1Disabled) .setMultiTenantAuthDisabled(this.multiTenantAuthDisabled) .setUserAssertion(this.userAssertion) .setConfigurationStore(this.configuration) .setPersistenceCache(this.sharedTokenCacheEnabled) .setClientOptions(this.clientOptions) .setHttpLogOptions(this.httpLogOptions) .setRetryOptions(this.retryOptions) .setRetryPolicy(this.retryPolicy) .setPerCallPolicies(this.perCallPolicies) .setPerRetryPolicies(this.perRetryPolicies); if (!getInstanceDiscovery()) { clone.disableInstanceDisovery(); } return clone; } }
Is it valid when no Condition, or no Action? If it is valid, should we let user create without calling them? Would avoid user write `define...().withMatchConditions().withActions().attach()`
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
}
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
I'm not sure, will check it. Thanks!
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
}
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
From [docs](https://learn.microsoft.com/en-us/azure/cdn/cdn-standard-rules-engine-reference#terminology) and Portal: `actions` is always required. For `matchConditions`: 1. for Global rule(order=0), it must be left blank, and makes sense since it's global and always will be triggered 2. for other rules(order=1,2,3,...,etc), it's required two alternatives for Global rule: 1. introduce `defineNewStandardRulesEngineGlobalRule().withActions(actions)` and `withoutStandardRulesEngineGlobalRule()`. 2. introduce `withoutMatchConditions().withActions(actions)`. Personally I prefer the first alternative.
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
}
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
Maybe make the MatchCondition stage optional? Then, user can just do `withActions(...).attach()` for first rule. If this way, we probably will mention this (blank for first, required for the rest) in javadoc of this `withMatchConditions`
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
}
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
Sure, sounds good!
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
}
public CdnStandardRulesEngineRuleImpl withActions(DeliveryRuleAction... actions) { List<DeliveryRuleAction> actionList = new ArrayList<>(); if (actions != null) { actionList.addAll(Arrays.asList(actions)); } innerModel().withActions(actionList); return this; }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
class CdnStandardRulesEngineRuleImpl extends ChildResourceImpl<DeliveryRule, CdnEndpointImpl, CdnEndpoint> implements CdnStandardRulesEngineRule, CdnStandardRulesEngineRule.Definition<CdnEndpointImpl>, CdnStandardRulesEngineRule.Update<CdnEndpointImpl> { CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, String name) { this(parent, new DeliveryRule().withName(name)); } CdnStandardRulesEngineRuleImpl(CdnEndpointImpl parent, DeliveryRule deliveryRule) { super(deliveryRule, parent); } @Override public CdnStandardRulesEngineRuleImpl withOrder(int order) { innerModel().withOrder(order); return this; } @Override public CdnStandardRulesEngineRuleImpl withMatchConditions(DeliveryRuleCondition... matchConditions) { List<DeliveryRuleCondition> conditions = new ArrayList<>(); if (matchConditions != null) { conditions.addAll(Arrays.asList(matchConditions)); } innerModel().withConditions(conditions); return this; } @Override @Override public String name() { return innerModel().name(); } @Override public CdnEndpointImpl attach() { return parent(); } }
What is this "else if" part used for? I assume `innerModel().deliveryPolicy()` be not empty would mean `standardRulesEngineRuleMap` be not empty (if user not modify it)? On the other hand, if `standardRulesEngineRuleMap` be empty (while `innerModel().deliveryPolicy()` not empty), does it mean user actually removed the rules? Hence it need to be handled in "if" clause?
public Mono<CdnEndpoint> updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) .withOriginPath(this.innerModel().originPath()) .withOriginHostHeader(this.innerModel().originHostHeader()) .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) .withGeoFilters(this.innerModel().geoFilters()) .withOptimizationType(this.innerModel().optimizationType()) .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List<DeliveryRule> rules = this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); if (innerModel().deliveryPolicy() == null && !CoreUtils.isNullOrEmpty(this.standardRulesEngineRuleMap)) { endpointUpdateParameters.withDeliveryPolicy( new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(rules)); } else if (innerModel().deliveryPolicy() != null) { endpointUpdateParameters.withDeliveryPolicy( innerModel().deliveryPolicy() .withRules(rules)); } } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() .withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); Mono<EndpointInner> originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); Mono<EndpointInner> endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList) .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(itemToCreate.hostname()) ), 32, 32); Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name() ), 32, 32); Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) .then(Mono.empty()); return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) .last() .map(inner -> { self.setInner(inner); self.customDomainList.clear(); self.deletedCustomDomainList.clear(); return self; }); }
}
public Mono<CdnEndpoint> updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) .withOriginPath(this.innerModel().originPath()) .withOriginHostHeader(this.innerModel().originHostHeader()) .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) .withGeoFilters(this.innerModel().geoFilters()) .withOptimizationType(this.innerModel().optimizationType()) .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List<DeliveryRule> rules = this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); ensureDeliveryPolicy(); endpointUpdateParameters.withDeliveryPolicy( new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(rules)); } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() .withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); Mono<EndpointInner> originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); Mono<EndpointInner> endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList) .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(itemToCreate.hostname()) ), 32, 32); Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name() ), 32, 32); Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) .then(Mono.empty()); return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) .last() .map(inner -> { self.setInner(inner); self.customDomainList.clear(); self.deletedCustomDomainList.clear(); return self; }); }
class CdnEndpointImpl extends ExternalChildResourceImpl< CdnEndpoint, EndpointInner, CdnProfileImpl, CdnProfile> implements CdnEndpoint, CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>, CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List<CustomDomainInner> customDomainList; private List<CustomDomainInner> deletedCustomDomainList; private final Map<String, DeliveryRule> standardRulesEngineRuleMap = new HashMap<>(); CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) { super(name, parent, inner); this.customDomainList = new ArrayList<>(); this.deletedCustomDomainList = new ArrayList<>(); initializeRuleMapForStandardMicrosoftSku(); } @Override public String id() { return this.innerModel().id(); } @Override public Mono<CdnEndpoint> createResourceAsync() { final CdnEndpointImpl self = this; if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()))); } return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() .getCustomDomains().createAsync( self.parent().resourceGroupName(), self.parent().name(), self.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) .then(self.parent().manager().serviceClient() .getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; })); }); } @Override @Override public Mono<Void> deleteResourceAsync() { return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono<CdnEndpoint> refreshAsync() { final CdnEndpointImpl self = this; return super.refreshAsync() .flatMap(cdnEndpoint -> { self.customDomainList.clear(); self.deletedCustomDomainList.clear(); initializeRuleMapForStandardMicrosoftSku(); return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name() ) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; }); }); } @Override protected Mono<EndpointInner> getInnerAsync() { return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable<ResourceUsage> listResourceUsage() { return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @Override public Map<String, DeliveryRule> standardRulesEngineRules() { return Collections.unmodifiableMap(this.standardRulesEngineRuleMap); } @Override public CdnProfileImpl attach() { return this.parent(); } @Override public String originHostHeader() { return this.innerModel().originHostHeader(); } @Override public String originPath() { return this.innerModel().originPath(); } @Override public Set<String> contentTypesToCompress() { List<String> contentTypes = this.innerModel().contentTypesToCompress(); Set<String> set = new HashSet<>(); if (contentTypes != null) { set.addAll(contentTypes); } return Collections.unmodifiableSet(set); } @Override public boolean isCompressionEnabled() { return this.innerModel().isCompressionEnabled(); } @Override public boolean isHttpAllowed() { return this.innerModel().isHttpAllowed(); } @Override public boolean isHttpsAllowed() { return this.innerModel().isHttpsAllowed(); } @Override public QueryStringCachingBehavior queryStringCachingBehavior() { return this.innerModel().queryStringCachingBehavior(); } @Override public String optimizationType() { if (this.innerModel().optimizationType() == null) { return null; } return this.innerModel().optimizationType().toString(); } @Override public List<GeoFilter> geoFilters() { return this.innerModel().geoFilters(); } @Override public String hostname() { return this.innerModel().hostname(); } @Override public EndpointResourceState resourceState() { return this.innerModel().resourceState(); } @Override public String provisioningState() { return this.innerModel().provisioningState() == null ? null : this.innerModel().provisioningState().toString(); } @Override public String originHostName() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { return this.innerModel().origins().get(0).hostname(); } return null; } @Override public int httpPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpPort = this.innerModel().origins().get(0).httpPort(); return (httpPort != null) ? httpPort : 0; } return 0; } @Override public int httpsPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpsPort = this.innerModel().origins().get(0).httpsPort(); return (httpsPort != null) ? httpsPort : 0; } return 0; } @Override public Set<String> customDomains() { Set<String> set = new HashSet<>(); for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } return Collections.unmodifiableSet(set); } @Override public void start() { this.parent().startEndpoint(this.name()); } @Override public Mono<Void> startAsync() { return this.parent().startEndpointAsync(this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return this.parent().stopEndpointAsync(this.name()); } @Override public void purgeContent(Set<String> contentPaths) { if (contentPaths != null) { this.purgeContentAsync(contentPaths).block(); } } @Override public Mono<Void> purgeContentAsync(Set<String> contentPaths) { return this.parent().purgeEndpointContentAsync(this.name(), contentPaths); } @Override public void loadContent(Set<String> contentPaths) { this.loadContentAsync(contentPaths).block(); } @Override public Mono<Void> loadContentAsync(Set<String> contentPaths) { return this.parent().loadEndpointContentAsync(this.name(), contentPaths); } @Override public CustomDomainValidationResult validateCustomDomain(String hostName) { return this.validateCustomDomainAsync(hostName).block(); } @Override public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) { return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName); } @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { this.innerModel().origins().add( new DeepCreatedOrigin() .withName(originName) .withHostname(hostname)); return this; } @Override public CdnEndpointImpl withOrigin(String hostname) { return this.withOrigin("origin", hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) { return this.withOrigin(originName, hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String hostname) { return this.withOrigin(hostname); } @Override public CdnEndpointImpl withOriginPath(String originPath) { this.innerModel().withOriginPath(originPath); return this; } @Override public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) { this.innerModel().withIsHttpAllowed(httpAllowed); return this; } @Override public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) { this.innerModel().withIsHttpsAllowed(httpsAllowed); return this; } @Override public CdnEndpointImpl withHttpPort(int httpPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpPort(httpPort); } return this; } @Override public CdnEndpointImpl withHttpsPort(int httpsPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpsPort(httpsPort); } return this; } @Override public CdnEndpointImpl withHostHeader(String hostHeader) { this.innerModel().withOriginHostHeader(hostHeader); return this; } @Override public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) { List<String> list = null; if (contentTypesToCompress != null) { list = new ArrayList<>(contentTypesToCompress); } this.innerModel().withContentTypesToCompress(list); return this; } @Override public CdnEndpointImpl withoutContentTypesToCompress() { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().clear(); } return this; } @Override public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() == null) { this.innerModel().withContentTypesToCompress(new ArrayList<>()); } this.innerModel().contentTypesToCompress().add(contentTypeToCompress); return this; } @Override public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().remove(contentTypeToCompress); } return this; } @Override public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) { this.innerModel().withIsCompressionEnabled(compressionEnabled); return this; } @Override public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) { this.innerModel().withQueryStringCachingBehavior(cachingBehavior); return this; } @Override public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) { List<GeoFilter> list = null; if (geoFilters != null) { list = new ArrayList<>(geoFilters); } this.innerModel().withGeoFilters(list); return this; } @Override public CdnEndpointImpl withoutGeoFilters() { if (this.innerModel().geoFilters() != null) { this.innerModel().geoFilters().clear(); } return this; } @Override public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } geoFilter.countryCodes().add(countryCode.toString()); this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withGeoFilter( String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } else { geoFilter.countryCodes().clear(); } for (CountryIsoCode countryCode : countryCodes) { geoFilter.countryCodes().add(countryCode.toString()); } this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withoutGeoFilter(String relativePath) { this.innerModel().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath)); return this; } @Override public CdnEndpointImpl withCustomDomain(String hostName) { this.customDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } @Override @SuppressWarnings("unchecked") public CdnStandardRulesEngineRuleImpl defineNewStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } CdnStandardRulesEngineRuleImpl deliveryRule = new CdnStandardRulesEngineRuleImpl(this, name); this.standardRulesEngineRuleMap.put(name, deliveryRule.innerModel()); return deliveryRule; } @Override @SuppressWarnings("unchecked") public CdnStandardRulesEngineRuleImpl updateStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } return new CdnStandardRulesEngineRuleImpl(this, standardRulesEngineRules().get(name)); } @Override public CdnEndpointImpl withoutStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } this.standardRulesEngineRuleMap.remove(name); return this; } @Override public CdnEndpointImpl withoutCustomDomain(String hostName) { deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) { if (this.innerModel().geoFilters() == null) { this.innerModel().withGeoFilters(new ArrayList<>()); } GeoFilter geoFilter = null; for (GeoFilter filter : this.innerModel().geoFilters()) { if (filter.relativePath().equals(relativePath)) { geoFilter = filter; break; } } if (geoFilter == null) { geoFilter = new GeoFilter(); } else { this.innerModel().geoFilters().remove(geoFilter); } geoFilter.withRelativePath(relativePath) .withAction(action); return geoFilter; } private void initializeRuleMapForStandardMicrosoftSku() { standardRulesEngineRuleMap.clear(); if (isStandardMicrosoftSku() && innerModel().deliveryPolicy() != null && innerModel().deliveryPolicy().rules() != null) { for (DeliveryRule rule : innerModel().deliveryPolicy().rules()) { this.standardRulesEngineRuleMap.put(rule.name(), rule); } } } private boolean isStandardMicrosoftSku() { return SkuName.STANDARD_MICROSOFT.equals(parent().sku().name()); } }
class CdnEndpointImpl extends ExternalChildResourceImpl< CdnEndpoint, EndpointInner, CdnProfileImpl, CdnProfile> implements CdnEndpoint, CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>, CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List<CustomDomainInner> customDomainList; private List<CustomDomainInner> deletedCustomDomainList; private final Map<String, DeliveryRule> standardRulesEngineRuleMap = new HashMap<>(); CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) { super(name, parent, inner); this.customDomainList = new ArrayList<>(); this.deletedCustomDomainList = new ArrayList<>(); initializeRuleMapForStandardMicrosoftSku(); } @Override public String id() { return this.innerModel().id(); } @Override public Mono<CdnEndpoint> createResourceAsync() { final CdnEndpointImpl self = this; if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()))); } return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() .getCustomDomains().createAsync( self.parent().resourceGroupName(), self.parent().name(), self.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) .then(self.parent().manager().serviceClient() .getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; })); }); } @Override @Override public Mono<Void> deleteResourceAsync() { return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono<CdnEndpoint> refreshAsync() { final CdnEndpointImpl self = this; return super.refreshAsync() .flatMap(cdnEndpoint -> { self.customDomainList.clear(); self.deletedCustomDomainList.clear(); initializeRuleMapForStandardMicrosoftSku(); return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name() ) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; }); }); } @Override protected Mono<EndpointInner> getInnerAsync() { return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable<ResourceUsage> listResourceUsage() { return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @Override public Map<String, DeliveryRule> standardRulesEngineRules() { return Collections.unmodifiableMap(this.standardRulesEngineRuleMap); } @Override public CdnProfileImpl attach() { return this.parent(); } @Override public String originHostHeader() { return this.innerModel().originHostHeader(); } @Override public String originPath() { return this.innerModel().originPath(); } @Override public Set<String> contentTypesToCompress() { List<String> contentTypes = this.innerModel().contentTypesToCompress(); Set<String> set = new HashSet<>(); if (contentTypes != null) { set.addAll(contentTypes); } return Collections.unmodifiableSet(set); } @Override public boolean isCompressionEnabled() { return this.innerModel().isCompressionEnabled(); } @Override public boolean isHttpAllowed() { return this.innerModel().isHttpAllowed(); } @Override public boolean isHttpsAllowed() { return this.innerModel().isHttpsAllowed(); } @Override public QueryStringCachingBehavior queryStringCachingBehavior() { return this.innerModel().queryStringCachingBehavior(); } @Override public String optimizationType() { if (this.innerModel().optimizationType() == null) { return null; } return this.innerModel().optimizationType().toString(); } @Override public List<GeoFilter> geoFilters() { return this.innerModel().geoFilters(); } @Override public String hostname() { return this.innerModel().hostname(); } @Override public EndpointResourceState resourceState() { return this.innerModel().resourceState(); } @Override public String provisioningState() { return this.innerModel().provisioningState() == null ? null : this.innerModel().provisioningState().toString(); } @Override public String originHostName() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { return this.innerModel().origins().get(0).hostname(); } return null; } @Override public int httpPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpPort = this.innerModel().origins().get(0).httpPort(); return (httpPort != null) ? httpPort : 0; } return 0; } @Override public int httpsPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpsPort = this.innerModel().origins().get(0).httpsPort(); return (httpsPort != null) ? httpsPort : 0; } return 0; } @Override public Set<String> customDomains() { Set<String> set = new HashSet<>(); for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } return Collections.unmodifiableSet(set); } @Override public void start() { this.parent().startEndpoint(this.name()); } @Override public Mono<Void> startAsync() { return this.parent().startEndpointAsync(this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return this.parent().stopEndpointAsync(this.name()); } @Override public void purgeContent(Set<String> contentPaths) { if (contentPaths != null) { this.purgeContentAsync(contentPaths).block(); } } @Override public Mono<Void> purgeContentAsync(Set<String> contentPaths) { return this.parent().purgeEndpointContentAsync(this.name(), contentPaths); } @Override public void loadContent(Set<String> contentPaths) { this.loadContentAsync(contentPaths).block(); } @Override public Mono<Void> loadContentAsync(Set<String> contentPaths) { return this.parent().loadEndpointContentAsync(this.name(), contentPaths); } @Override public CustomDomainValidationResult validateCustomDomain(String hostName) { return this.validateCustomDomainAsync(hostName).block(); } @Override public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) { return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName); } @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { this.innerModel().origins().add( new DeepCreatedOrigin() .withName(originName) .withHostname(hostname)); return this; } @Override public CdnEndpointImpl withOrigin(String hostname) { return this.withOrigin("origin", hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) { return this.withOrigin(originName, hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String hostname) { return this.withOrigin(hostname); } @Override public CdnEndpointImpl withOriginPath(String originPath) { this.innerModel().withOriginPath(originPath); return this; } @Override public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) { this.innerModel().withIsHttpAllowed(httpAllowed); return this; } @Override public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) { this.innerModel().withIsHttpsAllowed(httpsAllowed); return this; } @Override public CdnEndpointImpl withHttpPort(int httpPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpPort(httpPort); } return this; } @Override public CdnEndpointImpl withHttpsPort(int httpsPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpsPort(httpsPort); } return this; } @Override public CdnEndpointImpl withHostHeader(String hostHeader) { this.innerModel().withOriginHostHeader(hostHeader); return this; } @Override public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) { List<String> list = null; if (contentTypesToCompress != null) { list = new ArrayList<>(contentTypesToCompress); } this.innerModel().withContentTypesToCompress(list); return this; } @Override public CdnEndpointImpl withoutContentTypesToCompress() { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().clear(); } return this; } @Override public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() == null) { this.innerModel().withContentTypesToCompress(new ArrayList<>()); } this.innerModel().contentTypesToCompress().add(contentTypeToCompress); return this; } @Override public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().remove(contentTypeToCompress); } return this; } @Override public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) { this.innerModel().withIsCompressionEnabled(compressionEnabled); return this; } @Override public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) { this.innerModel().withQueryStringCachingBehavior(cachingBehavior); return this; } @Override public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) { List<GeoFilter> list = null; if (geoFilters != null) { list = new ArrayList<>(geoFilters); } this.innerModel().withGeoFilters(list); return this; } @Override public CdnEndpointImpl withoutGeoFilters() { if (this.innerModel().geoFilters() != null) { this.innerModel().geoFilters().clear(); } return this; } @Override public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } geoFilter.countryCodes().add(countryCode.toString()); this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withGeoFilter( String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } else { geoFilter.countryCodes().clear(); } for (CountryIsoCode countryCode : countryCodes) { geoFilter.countryCodes().add(countryCode.toString()); } this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withoutGeoFilter(String relativePath) { this.innerModel().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath)); return this; } @Override public CdnEndpointImpl withCustomDomain(String hostName) { this.customDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } @Override public CdnStandardRulesEngineRuleImpl defineNewStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); CdnStandardRulesEngineRuleImpl deliveryRule = new CdnStandardRulesEngineRuleImpl(this, name); this.standardRulesEngineRuleMap.put(name, deliveryRule.innerModel()); return deliveryRule; } @Override public CdnStandardRulesEngineRuleImpl updateStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); return new CdnStandardRulesEngineRuleImpl(this, standardRulesEngineRules().get(name)); } @Override public CdnEndpointImpl withoutStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); this.standardRulesEngineRuleMap.remove(name); return this; } @Override public CdnEndpointImpl withoutCustomDomain(String hostName) { deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) { if (this.innerModel().geoFilters() == null) { this.innerModel().withGeoFilters(new ArrayList<>()); } GeoFilter geoFilter = null; for (GeoFilter filter : this.innerModel().geoFilters()) { if (filter.relativePath().equals(relativePath)) { geoFilter = filter; break; } } if (geoFilter == null) { geoFilter = new GeoFilter(); } else { this.innerModel().geoFilters().remove(geoFilter); } geoFilter.withRelativePath(relativePath) .withAction(action); return geoFilter; } private void initializeRuleMapForStandardMicrosoftSku() { standardRulesEngineRuleMap.clear(); if (isStandardMicrosoftSku() && innerModel().deliveryPolicy() != null && innerModel().deliveryPolicy().rules() != null) { for (DeliveryRule rule : innerModel().deliveryPolicy().rules()) { this.standardRulesEngineRuleMap.put(rule.name(), rule); } } } private boolean isStandardMicrosoftSku() { return SkuName.STANDARD_MICROSOFT.equals(parent().sku().name()); } private void throwIfNotStandardMicrosoftSku() { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format( "Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } } private void ensureDeliveryPolicy() { if (innerModel().deliveryPolicy() == null) { innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy()); } } }
that is 3rd of this, use a method?
public CdnEndpointImpl withoutStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } this.standardRulesEngineRuleMap.remove(name); return this; }
}
public CdnEndpointImpl withoutStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); this.standardRulesEngineRuleMap.remove(name); return this; }
class CdnEndpointImpl extends ExternalChildResourceImpl< CdnEndpoint, EndpointInner, CdnProfileImpl, CdnProfile> implements CdnEndpoint, CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>, CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List<CustomDomainInner> customDomainList; private List<CustomDomainInner> deletedCustomDomainList; private final Map<String, DeliveryRule> standardRulesEngineRuleMap = new HashMap<>(); CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) { super(name, parent, inner); this.customDomainList = new ArrayList<>(); this.deletedCustomDomainList = new ArrayList<>(); initializeRuleMapForStandardMicrosoftSku(); } @Override public String id() { return this.innerModel().id(); } @Override public Mono<CdnEndpoint> createResourceAsync() { final CdnEndpointImpl self = this; if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()))); } return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() .getCustomDomains().createAsync( self.parent().resourceGroupName(), self.parent().name(), self.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) .then(self.parent().manager().serviceClient() .getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; })); }); } @Override public Mono<CdnEndpoint> updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) .withOriginPath(this.innerModel().originPath()) .withOriginHostHeader(this.innerModel().originHostHeader()) .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) .withGeoFilters(this.innerModel().geoFilters()) .withOptimizationType(this.innerModel().optimizationType()) .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List<DeliveryRule> rules = this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); if (innerModel().deliveryPolicy() == null && !CoreUtils.isNullOrEmpty(this.standardRulesEngineRuleMap)) { endpointUpdateParameters.withDeliveryPolicy( new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(rules)); } else if (innerModel().deliveryPolicy() != null) { endpointUpdateParameters.withDeliveryPolicy( innerModel().deliveryPolicy() .withRules(rules)); } } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() .withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); Mono<EndpointInner> originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); Mono<EndpointInner> endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList) .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(itemToCreate.hostname()) ), 32, 32); Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name() ), 32, 32); Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) .then(Mono.empty()); return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) .last() .map(inner -> { self.setInner(inner); self.customDomainList.clear(); self.deletedCustomDomainList.clear(); return self; }); } @Override public Mono<Void> deleteResourceAsync() { return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono<CdnEndpoint> refreshAsync() { final CdnEndpointImpl self = this; return super.refreshAsync() .flatMap(cdnEndpoint -> { self.customDomainList.clear(); self.deletedCustomDomainList.clear(); initializeRuleMapForStandardMicrosoftSku(); return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name() ) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; }); }); } @Override protected Mono<EndpointInner> getInnerAsync() { return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable<ResourceUsage> listResourceUsage() { return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @Override public Map<String, DeliveryRule> standardRulesEngineRules() { return Collections.unmodifiableMap(this.standardRulesEngineRuleMap); } @Override public CdnProfileImpl attach() { return this.parent(); } @Override public String originHostHeader() { return this.innerModel().originHostHeader(); } @Override public String originPath() { return this.innerModel().originPath(); } @Override public Set<String> contentTypesToCompress() { List<String> contentTypes = this.innerModel().contentTypesToCompress(); Set<String> set = new HashSet<>(); if (contentTypes != null) { set.addAll(contentTypes); } return Collections.unmodifiableSet(set); } @Override public boolean isCompressionEnabled() { return this.innerModel().isCompressionEnabled(); } @Override public boolean isHttpAllowed() { return this.innerModel().isHttpAllowed(); } @Override public boolean isHttpsAllowed() { return this.innerModel().isHttpsAllowed(); } @Override public QueryStringCachingBehavior queryStringCachingBehavior() { return this.innerModel().queryStringCachingBehavior(); } @Override public String optimizationType() { if (this.innerModel().optimizationType() == null) { return null; } return this.innerModel().optimizationType().toString(); } @Override public List<GeoFilter> geoFilters() { return this.innerModel().geoFilters(); } @Override public String hostname() { return this.innerModel().hostname(); } @Override public EndpointResourceState resourceState() { return this.innerModel().resourceState(); } @Override public String provisioningState() { return this.innerModel().provisioningState() == null ? null : this.innerModel().provisioningState().toString(); } @Override public String originHostName() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { return this.innerModel().origins().get(0).hostname(); } return null; } @Override public int httpPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpPort = this.innerModel().origins().get(0).httpPort(); return (httpPort != null) ? httpPort : 0; } return 0; } @Override public int httpsPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpsPort = this.innerModel().origins().get(0).httpsPort(); return (httpsPort != null) ? httpsPort : 0; } return 0; } @Override public Set<String> customDomains() { Set<String> set = new HashSet<>(); for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } return Collections.unmodifiableSet(set); } @Override public void start() { this.parent().startEndpoint(this.name()); } @Override public Mono<Void> startAsync() { return this.parent().startEndpointAsync(this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return this.parent().stopEndpointAsync(this.name()); } @Override public void purgeContent(Set<String> contentPaths) { if (contentPaths != null) { this.purgeContentAsync(contentPaths).block(); } } @Override public Mono<Void> purgeContentAsync(Set<String> contentPaths) { return this.parent().purgeEndpointContentAsync(this.name(), contentPaths); } @Override public void loadContent(Set<String> contentPaths) { this.loadContentAsync(contentPaths).block(); } @Override public Mono<Void> loadContentAsync(Set<String> contentPaths) { return this.parent().loadEndpointContentAsync(this.name(), contentPaths); } @Override public CustomDomainValidationResult validateCustomDomain(String hostName) { return this.validateCustomDomainAsync(hostName).block(); } @Override public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) { return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName); } @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { this.innerModel().origins().add( new DeepCreatedOrigin() .withName(originName) .withHostname(hostname)); return this; } @Override public CdnEndpointImpl withOrigin(String hostname) { return this.withOrigin("origin", hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) { return this.withOrigin(originName, hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String hostname) { return this.withOrigin(hostname); } @Override public CdnEndpointImpl withOriginPath(String originPath) { this.innerModel().withOriginPath(originPath); return this; } @Override public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) { this.innerModel().withIsHttpAllowed(httpAllowed); return this; } @Override public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) { this.innerModel().withIsHttpsAllowed(httpsAllowed); return this; } @Override public CdnEndpointImpl withHttpPort(int httpPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpPort(httpPort); } return this; } @Override public CdnEndpointImpl withHttpsPort(int httpsPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpsPort(httpsPort); } return this; } @Override public CdnEndpointImpl withHostHeader(String hostHeader) { this.innerModel().withOriginHostHeader(hostHeader); return this; } @Override public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) { List<String> list = null; if (contentTypesToCompress != null) { list = new ArrayList<>(contentTypesToCompress); } this.innerModel().withContentTypesToCompress(list); return this; } @Override public CdnEndpointImpl withoutContentTypesToCompress() { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().clear(); } return this; } @Override public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() == null) { this.innerModel().withContentTypesToCompress(new ArrayList<>()); } this.innerModel().contentTypesToCompress().add(contentTypeToCompress); return this; } @Override public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().remove(contentTypeToCompress); } return this; } @Override public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) { this.innerModel().withIsCompressionEnabled(compressionEnabled); return this; } @Override public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) { this.innerModel().withQueryStringCachingBehavior(cachingBehavior); return this; } @Override public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) { List<GeoFilter> list = null; if (geoFilters != null) { list = new ArrayList<>(geoFilters); } this.innerModel().withGeoFilters(list); return this; } @Override public CdnEndpointImpl withoutGeoFilters() { if (this.innerModel().geoFilters() != null) { this.innerModel().geoFilters().clear(); } return this; } @Override public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } geoFilter.countryCodes().add(countryCode.toString()); this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withGeoFilter( String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } else { geoFilter.countryCodes().clear(); } for (CountryIsoCode countryCode : countryCodes) { geoFilter.countryCodes().add(countryCode.toString()); } this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withoutGeoFilter(String relativePath) { this.innerModel().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath)); return this; } @Override public CdnEndpointImpl withCustomDomain(String hostName) { this.customDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } @Override @SuppressWarnings("unchecked") public CdnStandardRulesEngineRuleImpl defineNewStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } CdnStandardRulesEngineRuleImpl deliveryRule = new CdnStandardRulesEngineRuleImpl(this, name); this.standardRulesEngineRuleMap.put(name, deliveryRule.innerModel()); return deliveryRule; } @Override @SuppressWarnings("unchecked") public CdnStandardRulesEngineRuleImpl updateStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } return new CdnStandardRulesEngineRuleImpl(this, standardRulesEngineRules().get(name)); } @Override @Override public CdnEndpointImpl withoutCustomDomain(String hostName) { deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) { if (this.innerModel().geoFilters() == null) { this.innerModel().withGeoFilters(new ArrayList<>()); } GeoFilter geoFilter = null; for (GeoFilter filter : this.innerModel().geoFilters()) { if (filter.relativePath().equals(relativePath)) { geoFilter = filter; break; } } if (geoFilter == null) { geoFilter = new GeoFilter(); } else { this.innerModel().geoFilters().remove(geoFilter); } geoFilter.withRelativePath(relativePath) .withAction(action); return geoFilter; } private void initializeRuleMapForStandardMicrosoftSku() { standardRulesEngineRuleMap.clear(); if (isStandardMicrosoftSku() && innerModel().deliveryPolicy() != null && innerModel().deliveryPolicy().rules() != null) { for (DeliveryRule rule : innerModel().deliveryPolicy().rules()) { this.standardRulesEngineRuleMap.put(rule.name(), rule); } } } private boolean isStandardMicrosoftSku() { return SkuName.STANDARD_MICROSOFT.equals(parent().sku().name()); } }
class CdnEndpointImpl extends ExternalChildResourceImpl< CdnEndpoint, EndpointInner, CdnProfileImpl, CdnProfile> implements CdnEndpoint, CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>, CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List<CustomDomainInner> customDomainList; private List<CustomDomainInner> deletedCustomDomainList; private final Map<String, DeliveryRule> standardRulesEngineRuleMap = new HashMap<>(); CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) { super(name, parent, inner); this.customDomainList = new ArrayList<>(); this.deletedCustomDomainList = new ArrayList<>(); initializeRuleMapForStandardMicrosoftSku(); } @Override public String id() { return this.innerModel().id(); } @Override public Mono<CdnEndpoint> createResourceAsync() { final CdnEndpointImpl self = this; if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()))); } return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() .getCustomDomains().createAsync( self.parent().resourceGroupName(), self.parent().name(), self.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) .then(self.parent().manager().serviceClient() .getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; })); }); } @Override public Mono<CdnEndpoint> updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) .withOriginPath(this.innerModel().originPath()) .withOriginHostHeader(this.innerModel().originHostHeader()) .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) .withGeoFilters(this.innerModel().geoFilters()) .withOptimizationType(this.innerModel().optimizationType()) .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List<DeliveryRule> rules = this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); ensureDeliveryPolicy(); endpointUpdateParameters.withDeliveryPolicy( new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(rules)); } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() .withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); Mono<EndpointInner> originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); Mono<EndpointInner> endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList) .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(itemToCreate.hostname()) ), 32, 32); Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name() ), 32, 32); Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) .then(Mono.empty()); return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) .last() .map(inner -> { self.setInner(inner); self.customDomainList.clear(); self.deletedCustomDomainList.clear(); return self; }); } @Override public Mono<Void> deleteResourceAsync() { return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono<CdnEndpoint> refreshAsync() { final CdnEndpointImpl self = this; return super.refreshAsync() .flatMap(cdnEndpoint -> { self.customDomainList.clear(); self.deletedCustomDomainList.clear(); initializeRuleMapForStandardMicrosoftSku(); return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name() ) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; }); }); } @Override protected Mono<EndpointInner> getInnerAsync() { return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable<ResourceUsage> listResourceUsage() { return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @Override public Map<String, DeliveryRule> standardRulesEngineRules() { return Collections.unmodifiableMap(this.standardRulesEngineRuleMap); } @Override public CdnProfileImpl attach() { return this.parent(); } @Override public String originHostHeader() { return this.innerModel().originHostHeader(); } @Override public String originPath() { return this.innerModel().originPath(); } @Override public Set<String> contentTypesToCompress() { List<String> contentTypes = this.innerModel().contentTypesToCompress(); Set<String> set = new HashSet<>(); if (contentTypes != null) { set.addAll(contentTypes); } return Collections.unmodifiableSet(set); } @Override public boolean isCompressionEnabled() { return this.innerModel().isCompressionEnabled(); } @Override public boolean isHttpAllowed() { return this.innerModel().isHttpAllowed(); } @Override public boolean isHttpsAllowed() { return this.innerModel().isHttpsAllowed(); } @Override public QueryStringCachingBehavior queryStringCachingBehavior() { return this.innerModel().queryStringCachingBehavior(); } @Override public String optimizationType() { if (this.innerModel().optimizationType() == null) { return null; } return this.innerModel().optimizationType().toString(); } @Override public List<GeoFilter> geoFilters() { return this.innerModel().geoFilters(); } @Override public String hostname() { return this.innerModel().hostname(); } @Override public EndpointResourceState resourceState() { return this.innerModel().resourceState(); } @Override public String provisioningState() { return this.innerModel().provisioningState() == null ? null : this.innerModel().provisioningState().toString(); } @Override public String originHostName() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { return this.innerModel().origins().get(0).hostname(); } return null; } @Override public int httpPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpPort = this.innerModel().origins().get(0).httpPort(); return (httpPort != null) ? httpPort : 0; } return 0; } @Override public int httpsPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpsPort = this.innerModel().origins().get(0).httpsPort(); return (httpsPort != null) ? httpsPort : 0; } return 0; } @Override public Set<String> customDomains() { Set<String> set = new HashSet<>(); for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } return Collections.unmodifiableSet(set); } @Override public void start() { this.parent().startEndpoint(this.name()); } @Override public Mono<Void> startAsync() { return this.parent().startEndpointAsync(this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return this.parent().stopEndpointAsync(this.name()); } @Override public void purgeContent(Set<String> contentPaths) { if (contentPaths != null) { this.purgeContentAsync(contentPaths).block(); } } @Override public Mono<Void> purgeContentAsync(Set<String> contentPaths) { return this.parent().purgeEndpointContentAsync(this.name(), contentPaths); } @Override public void loadContent(Set<String> contentPaths) { this.loadContentAsync(contentPaths).block(); } @Override public Mono<Void> loadContentAsync(Set<String> contentPaths) { return this.parent().loadEndpointContentAsync(this.name(), contentPaths); } @Override public CustomDomainValidationResult validateCustomDomain(String hostName) { return this.validateCustomDomainAsync(hostName).block(); } @Override public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) { return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName); } @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { this.innerModel().origins().add( new DeepCreatedOrigin() .withName(originName) .withHostname(hostname)); return this; } @Override public CdnEndpointImpl withOrigin(String hostname) { return this.withOrigin("origin", hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) { return this.withOrigin(originName, hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String hostname) { return this.withOrigin(hostname); } @Override public CdnEndpointImpl withOriginPath(String originPath) { this.innerModel().withOriginPath(originPath); return this; } @Override public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) { this.innerModel().withIsHttpAllowed(httpAllowed); return this; } @Override public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) { this.innerModel().withIsHttpsAllowed(httpsAllowed); return this; } @Override public CdnEndpointImpl withHttpPort(int httpPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpPort(httpPort); } return this; } @Override public CdnEndpointImpl withHttpsPort(int httpsPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpsPort(httpsPort); } return this; } @Override public CdnEndpointImpl withHostHeader(String hostHeader) { this.innerModel().withOriginHostHeader(hostHeader); return this; } @Override public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) { List<String> list = null; if (contentTypesToCompress != null) { list = new ArrayList<>(contentTypesToCompress); } this.innerModel().withContentTypesToCompress(list); return this; } @Override public CdnEndpointImpl withoutContentTypesToCompress() { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().clear(); } return this; } @Override public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() == null) { this.innerModel().withContentTypesToCompress(new ArrayList<>()); } this.innerModel().contentTypesToCompress().add(contentTypeToCompress); return this; } @Override public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().remove(contentTypeToCompress); } return this; } @Override public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) { this.innerModel().withIsCompressionEnabled(compressionEnabled); return this; } @Override public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) { this.innerModel().withQueryStringCachingBehavior(cachingBehavior); return this; } @Override public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) { List<GeoFilter> list = null; if (geoFilters != null) { list = new ArrayList<>(geoFilters); } this.innerModel().withGeoFilters(list); return this; } @Override public CdnEndpointImpl withoutGeoFilters() { if (this.innerModel().geoFilters() != null) { this.innerModel().geoFilters().clear(); } return this; } @Override public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } geoFilter.countryCodes().add(countryCode.toString()); this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withGeoFilter( String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } else { geoFilter.countryCodes().clear(); } for (CountryIsoCode countryCode : countryCodes) { geoFilter.countryCodes().add(countryCode.toString()); } this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withoutGeoFilter(String relativePath) { this.innerModel().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath)); return this; } @Override public CdnEndpointImpl withCustomDomain(String hostName) { this.customDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } @Override public CdnStandardRulesEngineRuleImpl defineNewStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); CdnStandardRulesEngineRuleImpl deliveryRule = new CdnStandardRulesEngineRuleImpl(this, name); this.standardRulesEngineRuleMap.put(name, deliveryRule.innerModel()); return deliveryRule; } @Override public CdnStandardRulesEngineRuleImpl updateStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); return new CdnStandardRulesEngineRuleImpl(this, standardRulesEngineRules().get(name)); } @Override @Override public CdnEndpointImpl withoutCustomDomain(String hostName) { deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) { if (this.innerModel().geoFilters() == null) { this.innerModel().withGeoFilters(new ArrayList<>()); } GeoFilter geoFilter = null; for (GeoFilter filter : this.innerModel().geoFilters()) { if (filter.relativePath().equals(relativePath)) { geoFilter = filter; break; } } if (geoFilter == null) { geoFilter = new GeoFilter(); } else { this.innerModel().geoFilters().remove(geoFilter); } geoFilter.withRelativePath(relativePath) .withAction(action); return geoFilter; } private void initializeRuleMapForStandardMicrosoftSku() { standardRulesEngineRuleMap.clear(); if (isStandardMicrosoftSku() && innerModel().deliveryPolicy() != null && innerModel().deliveryPolicy().rules() != null) { for (DeliveryRule rule : innerModel().deliveryPolicy().rules()) { this.standardRulesEngineRuleMap.put(rule.name(), rule); } } } private boolean isStandardMicrosoftSku() { return SkuName.STANDARD_MICROSOFT.equals(parent().sku().name()); } private void throwIfNotStandardMicrosoftSku() { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format( "Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } } private void ensureDeliveryPolicy() { if (innerModel().deliveryPolicy() == null) { innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy()); } } }
Got it. We can always replace deliveryPolicy with `standardRulesEngineRuleMap`.
public Mono<CdnEndpoint> updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) .withOriginPath(this.innerModel().originPath()) .withOriginHostHeader(this.innerModel().originHostHeader()) .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) .withGeoFilters(this.innerModel().geoFilters()) .withOptimizationType(this.innerModel().optimizationType()) .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List<DeliveryRule> rules = this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); if (innerModel().deliveryPolicy() == null && !CoreUtils.isNullOrEmpty(this.standardRulesEngineRuleMap)) { endpointUpdateParameters.withDeliveryPolicy( new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(rules)); } else if (innerModel().deliveryPolicy() != null) { endpointUpdateParameters.withDeliveryPolicy( innerModel().deliveryPolicy() .withRules(rules)); } } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() .withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); Mono<EndpointInner> originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); Mono<EndpointInner> endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList) .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(itemToCreate.hostname()) ), 32, 32); Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name() ), 32, 32); Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) .then(Mono.empty()); return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) .last() .map(inner -> { self.setInner(inner); self.customDomainList.clear(); self.deletedCustomDomainList.clear(); return self; }); }
}
public Mono<CdnEndpoint> updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) .withOriginPath(this.innerModel().originPath()) .withOriginHostHeader(this.innerModel().originHostHeader()) .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) .withGeoFilters(this.innerModel().geoFilters()) .withOptimizationType(this.innerModel().optimizationType()) .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List<DeliveryRule> rules = this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); ensureDeliveryPolicy(); endpointUpdateParameters.withDeliveryPolicy( new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(rules)); } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() .withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); Mono<EndpointInner> originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); Mono<EndpointInner> endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList) .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(itemToCreate.hostname()) ), 32, 32); Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name() ), 32, 32); Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) .then(Mono.empty()); return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) .last() .map(inner -> { self.setInner(inner); self.customDomainList.clear(); self.deletedCustomDomainList.clear(); return self; }); }
class CdnEndpointImpl extends ExternalChildResourceImpl< CdnEndpoint, EndpointInner, CdnProfileImpl, CdnProfile> implements CdnEndpoint, CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>, CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List<CustomDomainInner> customDomainList; private List<CustomDomainInner> deletedCustomDomainList; private final Map<String, DeliveryRule> standardRulesEngineRuleMap = new HashMap<>(); CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) { super(name, parent, inner); this.customDomainList = new ArrayList<>(); this.deletedCustomDomainList = new ArrayList<>(); initializeRuleMapForStandardMicrosoftSku(); } @Override public String id() { return this.innerModel().id(); } @Override public Mono<CdnEndpoint> createResourceAsync() { final CdnEndpointImpl self = this; if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()))); } return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() .getCustomDomains().createAsync( self.parent().resourceGroupName(), self.parent().name(), self.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) .then(self.parent().manager().serviceClient() .getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; })); }); } @Override @Override public Mono<Void> deleteResourceAsync() { return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono<CdnEndpoint> refreshAsync() { final CdnEndpointImpl self = this; return super.refreshAsync() .flatMap(cdnEndpoint -> { self.customDomainList.clear(); self.deletedCustomDomainList.clear(); initializeRuleMapForStandardMicrosoftSku(); return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name() ) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; }); }); } @Override protected Mono<EndpointInner> getInnerAsync() { return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable<ResourceUsage> listResourceUsage() { return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @Override public Map<String, DeliveryRule> standardRulesEngineRules() { return Collections.unmodifiableMap(this.standardRulesEngineRuleMap); } @Override public CdnProfileImpl attach() { return this.parent(); } @Override public String originHostHeader() { return this.innerModel().originHostHeader(); } @Override public String originPath() { return this.innerModel().originPath(); } @Override public Set<String> contentTypesToCompress() { List<String> contentTypes = this.innerModel().contentTypesToCompress(); Set<String> set = new HashSet<>(); if (contentTypes != null) { set.addAll(contentTypes); } return Collections.unmodifiableSet(set); } @Override public boolean isCompressionEnabled() { return this.innerModel().isCompressionEnabled(); } @Override public boolean isHttpAllowed() { return this.innerModel().isHttpAllowed(); } @Override public boolean isHttpsAllowed() { return this.innerModel().isHttpsAllowed(); } @Override public QueryStringCachingBehavior queryStringCachingBehavior() { return this.innerModel().queryStringCachingBehavior(); } @Override public String optimizationType() { if (this.innerModel().optimizationType() == null) { return null; } return this.innerModel().optimizationType().toString(); } @Override public List<GeoFilter> geoFilters() { return this.innerModel().geoFilters(); } @Override public String hostname() { return this.innerModel().hostname(); } @Override public EndpointResourceState resourceState() { return this.innerModel().resourceState(); } @Override public String provisioningState() { return this.innerModel().provisioningState() == null ? null : this.innerModel().provisioningState().toString(); } @Override public String originHostName() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { return this.innerModel().origins().get(0).hostname(); } return null; } @Override public int httpPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpPort = this.innerModel().origins().get(0).httpPort(); return (httpPort != null) ? httpPort : 0; } return 0; } @Override public int httpsPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpsPort = this.innerModel().origins().get(0).httpsPort(); return (httpsPort != null) ? httpsPort : 0; } return 0; } @Override public Set<String> customDomains() { Set<String> set = new HashSet<>(); for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } return Collections.unmodifiableSet(set); } @Override public void start() { this.parent().startEndpoint(this.name()); } @Override public Mono<Void> startAsync() { return this.parent().startEndpointAsync(this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return this.parent().stopEndpointAsync(this.name()); } @Override public void purgeContent(Set<String> contentPaths) { if (contentPaths != null) { this.purgeContentAsync(contentPaths).block(); } } @Override public Mono<Void> purgeContentAsync(Set<String> contentPaths) { return this.parent().purgeEndpointContentAsync(this.name(), contentPaths); } @Override public void loadContent(Set<String> contentPaths) { this.loadContentAsync(contentPaths).block(); } @Override public Mono<Void> loadContentAsync(Set<String> contentPaths) { return this.parent().loadEndpointContentAsync(this.name(), contentPaths); } @Override public CustomDomainValidationResult validateCustomDomain(String hostName) { return this.validateCustomDomainAsync(hostName).block(); } @Override public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) { return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName); } @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { this.innerModel().origins().add( new DeepCreatedOrigin() .withName(originName) .withHostname(hostname)); return this; } @Override public CdnEndpointImpl withOrigin(String hostname) { return this.withOrigin("origin", hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) { return this.withOrigin(originName, hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String hostname) { return this.withOrigin(hostname); } @Override public CdnEndpointImpl withOriginPath(String originPath) { this.innerModel().withOriginPath(originPath); return this; } @Override public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) { this.innerModel().withIsHttpAllowed(httpAllowed); return this; } @Override public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) { this.innerModel().withIsHttpsAllowed(httpsAllowed); return this; } @Override public CdnEndpointImpl withHttpPort(int httpPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpPort(httpPort); } return this; } @Override public CdnEndpointImpl withHttpsPort(int httpsPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpsPort(httpsPort); } return this; } @Override public CdnEndpointImpl withHostHeader(String hostHeader) { this.innerModel().withOriginHostHeader(hostHeader); return this; } @Override public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) { List<String> list = null; if (contentTypesToCompress != null) { list = new ArrayList<>(contentTypesToCompress); } this.innerModel().withContentTypesToCompress(list); return this; } @Override public CdnEndpointImpl withoutContentTypesToCompress() { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().clear(); } return this; } @Override public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() == null) { this.innerModel().withContentTypesToCompress(new ArrayList<>()); } this.innerModel().contentTypesToCompress().add(contentTypeToCompress); return this; } @Override public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().remove(contentTypeToCompress); } return this; } @Override public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) { this.innerModel().withIsCompressionEnabled(compressionEnabled); return this; } @Override public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) { this.innerModel().withQueryStringCachingBehavior(cachingBehavior); return this; } @Override public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) { List<GeoFilter> list = null; if (geoFilters != null) { list = new ArrayList<>(geoFilters); } this.innerModel().withGeoFilters(list); return this; } @Override public CdnEndpointImpl withoutGeoFilters() { if (this.innerModel().geoFilters() != null) { this.innerModel().geoFilters().clear(); } return this; } @Override public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } geoFilter.countryCodes().add(countryCode.toString()); this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withGeoFilter( String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } else { geoFilter.countryCodes().clear(); } for (CountryIsoCode countryCode : countryCodes) { geoFilter.countryCodes().add(countryCode.toString()); } this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withoutGeoFilter(String relativePath) { this.innerModel().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath)); return this; } @Override public CdnEndpointImpl withCustomDomain(String hostName) { this.customDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } @Override @SuppressWarnings("unchecked") public CdnStandardRulesEngineRuleImpl defineNewStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } CdnStandardRulesEngineRuleImpl deliveryRule = new CdnStandardRulesEngineRuleImpl(this, name); this.standardRulesEngineRuleMap.put(name, deliveryRule.innerModel()); return deliveryRule; } @Override @SuppressWarnings("unchecked") public CdnStandardRulesEngineRuleImpl updateStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } return new CdnStandardRulesEngineRuleImpl(this, standardRulesEngineRules().get(name)); } @Override public CdnEndpointImpl withoutStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } this.standardRulesEngineRuleMap.remove(name); return this; } @Override public CdnEndpointImpl withoutCustomDomain(String hostName) { deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) { if (this.innerModel().geoFilters() == null) { this.innerModel().withGeoFilters(new ArrayList<>()); } GeoFilter geoFilter = null; for (GeoFilter filter : this.innerModel().geoFilters()) { if (filter.relativePath().equals(relativePath)) { geoFilter = filter; break; } } if (geoFilter == null) { geoFilter = new GeoFilter(); } else { this.innerModel().geoFilters().remove(geoFilter); } geoFilter.withRelativePath(relativePath) .withAction(action); return geoFilter; } private void initializeRuleMapForStandardMicrosoftSku() { standardRulesEngineRuleMap.clear(); if (isStandardMicrosoftSku() && innerModel().deliveryPolicy() != null && innerModel().deliveryPolicy().rules() != null) { for (DeliveryRule rule : innerModel().deliveryPolicy().rules()) { this.standardRulesEngineRuleMap.put(rule.name(), rule); } } } private boolean isStandardMicrosoftSku() { return SkuName.STANDARD_MICROSOFT.equals(parent().sku().name()); } }
class CdnEndpointImpl extends ExternalChildResourceImpl< CdnEndpoint, EndpointInner, CdnProfileImpl, CdnProfile> implements CdnEndpoint, CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>, CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List<CustomDomainInner> customDomainList; private List<CustomDomainInner> deletedCustomDomainList; private final Map<String, DeliveryRule> standardRulesEngineRuleMap = new HashMap<>(); CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) { super(name, parent, inner); this.customDomainList = new ArrayList<>(); this.deletedCustomDomainList = new ArrayList<>(); initializeRuleMapForStandardMicrosoftSku(); } @Override public String id() { return this.innerModel().id(); } @Override public Mono<CdnEndpoint> createResourceAsync() { final CdnEndpointImpl self = this; if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()))); } return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() .getCustomDomains().createAsync( self.parent().resourceGroupName(), self.parent().name(), self.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) .then(self.parent().manager().serviceClient() .getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; })); }); } @Override @Override public Mono<Void> deleteResourceAsync() { return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono<CdnEndpoint> refreshAsync() { final CdnEndpointImpl self = this; return super.refreshAsync() .flatMap(cdnEndpoint -> { self.customDomainList.clear(); self.deletedCustomDomainList.clear(); initializeRuleMapForStandardMicrosoftSku(); return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name() ) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; }); }); } @Override protected Mono<EndpointInner> getInnerAsync() { return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable<ResourceUsage> listResourceUsage() { return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @Override public Map<String, DeliveryRule> standardRulesEngineRules() { return Collections.unmodifiableMap(this.standardRulesEngineRuleMap); } @Override public CdnProfileImpl attach() { return this.parent(); } @Override public String originHostHeader() { return this.innerModel().originHostHeader(); } @Override public String originPath() { return this.innerModel().originPath(); } @Override public Set<String> contentTypesToCompress() { List<String> contentTypes = this.innerModel().contentTypesToCompress(); Set<String> set = new HashSet<>(); if (contentTypes != null) { set.addAll(contentTypes); } return Collections.unmodifiableSet(set); } @Override public boolean isCompressionEnabled() { return this.innerModel().isCompressionEnabled(); } @Override public boolean isHttpAllowed() { return this.innerModel().isHttpAllowed(); } @Override public boolean isHttpsAllowed() { return this.innerModel().isHttpsAllowed(); } @Override public QueryStringCachingBehavior queryStringCachingBehavior() { return this.innerModel().queryStringCachingBehavior(); } @Override public String optimizationType() { if (this.innerModel().optimizationType() == null) { return null; } return this.innerModel().optimizationType().toString(); } @Override public List<GeoFilter> geoFilters() { return this.innerModel().geoFilters(); } @Override public String hostname() { return this.innerModel().hostname(); } @Override public EndpointResourceState resourceState() { return this.innerModel().resourceState(); } @Override public String provisioningState() { return this.innerModel().provisioningState() == null ? null : this.innerModel().provisioningState().toString(); } @Override public String originHostName() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { return this.innerModel().origins().get(0).hostname(); } return null; } @Override public int httpPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpPort = this.innerModel().origins().get(0).httpPort(); return (httpPort != null) ? httpPort : 0; } return 0; } @Override public int httpsPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpsPort = this.innerModel().origins().get(0).httpsPort(); return (httpsPort != null) ? httpsPort : 0; } return 0; } @Override public Set<String> customDomains() { Set<String> set = new HashSet<>(); for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } return Collections.unmodifiableSet(set); } @Override public void start() { this.parent().startEndpoint(this.name()); } @Override public Mono<Void> startAsync() { return this.parent().startEndpointAsync(this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return this.parent().stopEndpointAsync(this.name()); } @Override public void purgeContent(Set<String> contentPaths) { if (contentPaths != null) { this.purgeContentAsync(contentPaths).block(); } } @Override public Mono<Void> purgeContentAsync(Set<String> contentPaths) { return this.parent().purgeEndpointContentAsync(this.name(), contentPaths); } @Override public void loadContent(Set<String> contentPaths) { this.loadContentAsync(contentPaths).block(); } @Override public Mono<Void> loadContentAsync(Set<String> contentPaths) { return this.parent().loadEndpointContentAsync(this.name(), contentPaths); } @Override public CustomDomainValidationResult validateCustomDomain(String hostName) { return this.validateCustomDomainAsync(hostName).block(); } @Override public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) { return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName); } @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { this.innerModel().origins().add( new DeepCreatedOrigin() .withName(originName) .withHostname(hostname)); return this; } @Override public CdnEndpointImpl withOrigin(String hostname) { return this.withOrigin("origin", hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) { return this.withOrigin(originName, hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String hostname) { return this.withOrigin(hostname); } @Override public CdnEndpointImpl withOriginPath(String originPath) { this.innerModel().withOriginPath(originPath); return this; } @Override public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) { this.innerModel().withIsHttpAllowed(httpAllowed); return this; } @Override public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) { this.innerModel().withIsHttpsAllowed(httpsAllowed); return this; } @Override public CdnEndpointImpl withHttpPort(int httpPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpPort(httpPort); } return this; } @Override public CdnEndpointImpl withHttpsPort(int httpsPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpsPort(httpsPort); } return this; } @Override public CdnEndpointImpl withHostHeader(String hostHeader) { this.innerModel().withOriginHostHeader(hostHeader); return this; } @Override public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) { List<String> list = null; if (contentTypesToCompress != null) { list = new ArrayList<>(contentTypesToCompress); } this.innerModel().withContentTypesToCompress(list); return this; } @Override public CdnEndpointImpl withoutContentTypesToCompress() { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().clear(); } return this; } @Override public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() == null) { this.innerModel().withContentTypesToCompress(new ArrayList<>()); } this.innerModel().contentTypesToCompress().add(contentTypeToCompress); return this; } @Override public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().remove(contentTypeToCompress); } return this; } @Override public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) { this.innerModel().withIsCompressionEnabled(compressionEnabled); return this; } @Override public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) { this.innerModel().withQueryStringCachingBehavior(cachingBehavior); return this; } @Override public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) { List<GeoFilter> list = null; if (geoFilters != null) { list = new ArrayList<>(geoFilters); } this.innerModel().withGeoFilters(list); return this; } @Override public CdnEndpointImpl withoutGeoFilters() { if (this.innerModel().geoFilters() != null) { this.innerModel().geoFilters().clear(); } return this; } @Override public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } geoFilter.countryCodes().add(countryCode.toString()); this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withGeoFilter( String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } else { geoFilter.countryCodes().clear(); } for (CountryIsoCode countryCode : countryCodes) { geoFilter.countryCodes().add(countryCode.toString()); } this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withoutGeoFilter(String relativePath) { this.innerModel().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath)); return this; } @Override public CdnEndpointImpl withCustomDomain(String hostName) { this.customDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } @Override public CdnStandardRulesEngineRuleImpl defineNewStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); CdnStandardRulesEngineRuleImpl deliveryRule = new CdnStandardRulesEngineRuleImpl(this, name); this.standardRulesEngineRuleMap.put(name, deliveryRule.innerModel()); return deliveryRule; } @Override public CdnStandardRulesEngineRuleImpl updateStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); return new CdnStandardRulesEngineRuleImpl(this, standardRulesEngineRules().get(name)); } @Override public CdnEndpointImpl withoutStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); this.standardRulesEngineRuleMap.remove(name); return this; } @Override public CdnEndpointImpl withoutCustomDomain(String hostName) { deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) { if (this.innerModel().geoFilters() == null) { this.innerModel().withGeoFilters(new ArrayList<>()); } GeoFilter geoFilter = null; for (GeoFilter filter : this.innerModel().geoFilters()) { if (filter.relativePath().equals(relativePath)) { geoFilter = filter; break; } } if (geoFilter == null) { geoFilter = new GeoFilter(); } else { this.innerModel().geoFilters().remove(geoFilter); } geoFilter.withRelativePath(relativePath) .withAction(action); return geoFilter; } private void initializeRuleMapForStandardMicrosoftSku() { standardRulesEngineRuleMap.clear(); if (isStandardMicrosoftSku() && innerModel().deliveryPolicy() != null && innerModel().deliveryPolicy().rules() != null) { for (DeliveryRule rule : innerModel().deliveryPolicy().rules()) { this.standardRulesEngineRuleMap.put(rule.name(), rule); } } } private boolean isStandardMicrosoftSku() { return SkuName.STANDARD_MICROSOFT.equals(parent().sku().name()); } private void throwIfNotStandardMicrosoftSku() { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format( "Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } } private void ensureDeliveryPolicy() { if (innerModel().deliveryPolicy() == null) { innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy()); } } }
Changed.
public CdnEndpointImpl withoutStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } this.standardRulesEngineRuleMap.remove(name); return this; }
}
public CdnEndpointImpl withoutStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); this.standardRulesEngineRuleMap.remove(name); return this; }
class CdnEndpointImpl extends ExternalChildResourceImpl< CdnEndpoint, EndpointInner, CdnProfileImpl, CdnProfile> implements CdnEndpoint, CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>, CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List<CustomDomainInner> customDomainList; private List<CustomDomainInner> deletedCustomDomainList; private final Map<String, DeliveryRule> standardRulesEngineRuleMap = new HashMap<>(); CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) { super(name, parent, inner); this.customDomainList = new ArrayList<>(); this.deletedCustomDomainList = new ArrayList<>(); initializeRuleMapForStandardMicrosoftSku(); } @Override public String id() { return this.innerModel().id(); } @Override public Mono<CdnEndpoint> createResourceAsync() { final CdnEndpointImpl self = this; if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()))); } return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() .getCustomDomains().createAsync( self.parent().resourceGroupName(), self.parent().name(), self.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) .then(self.parent().manager().serviceClient() .getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; })); }); } @Override public Mono<CdnEndpoint> updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) .withOriginPath(this.innerModel().originPath()) .withOriginHostHeader(this.innerModel().originHostHeader()) .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) .withGeoFilters(this.innerModel().geoFilters()) .withOptimizationType(this.innerModel().optimizationType()) .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List<DeliveryRule> rules = this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); if (innerModel().deliveryPolicy() == null && !CoreUtils.isNullOrEmpty(this.standardRulesEngineRuleMap)) { endpointUpdateParameters.withDeliveryPolicy( new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(rules)); } else if (innerModel().deliveryPolicy() != null) { endpointUpdateParameters.withDeliveryPolicy( innerModel().deliveryPolicy() .withRules(rules)); } } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() .withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); Mono<EndpointInner> originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); Mono<EndpointInner> endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList) .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(itemToCreate.hostname()) ), 32, 32); Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name() ), 32, 32); Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) .then(Mono.empty()); return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) .last() .map(inner -> { self.setInner(inner); self.customDomainList.clear(); self.deletedCustomDomainList.clear(); return self; }); } @Override public Mono<Void> deleteResourceAsync() { return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono<CdnEndpoint> refreshAsync() { final CdnEndpointImpl self = this; return super.refreshAsync() .flatMap(cdnEndpoint -> { self.customDomainList.clear(); self.deletedCustomDomainList.clear(); initializeRuleMapForStandardMicrosoftSku(); return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name() ) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; }); }); } @Override protected Mono<EndpointInner> getInnerAsync() { return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable<ResourceUsage> listResourceUsage() { return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @Override public Map<String, DeliveryRule> standardRulesEngineRules() { return Collections.unmodifiableMap(this.standardRulesEngineRuleMap); } @Override public CdnProfileImpl attach() { return this.parent(); } @Override public String originHostHeader() { return this.innerModel().originHostHeader(); } @Override public String originPath() { return this.innerModel().originPath(); } @Override public Set<String> contentTypesToCompress() { List<String> contentTypes = this.innerModel().contentTypesToCompress(); Set<String> set = new HashSet<>(); if (contentTypes != null) { set.addAll(contentTypes); } return Collections.unmodifiableSet(set); } @Override public boolean isCompressionEnabled() { return this.innerModel().isCompressionEnabled(); } @Override public boolean isHttpAllowed() { return this.innerModel().isHttpAllowed(); } @Override public boolean isHttpsAllowed() { return this.innerModel().isHttpsAllowed(); } @Override public QueryStringCachingBehavior queryStringCachingBehavior() { return this.innerModel().queryStringCachingBehavior(); } @Override public String optimizationType() { if (this.innerModel().optimizationType() == null) { return null; } return this.innerModel().optimizationType().toString(); } @Override public List<GeoFilter> geoFilters() { return this.innerModel().geoFilters(); } @Override public String hostname() { return this.innerModel().hostname(); } @Override public EndpointResourceState resourceState() { return this.innerModel().resourceState(); } @Override public String provisioningState() { return this.innerModel().provisioningState() == null ? null : this.innerModel().provisioningState().toString(); } @Override public String originHostName() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { return this.innerModel().origins().get(0).hostname(); } return null; } @Override public int httpPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpPort = this.innerModel().origins().get(0).httpPort(); return (httpPort != null) ? httpPort : 0; } return 0; } @Override public int httpsPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpsPort = this.innerModel().origins().get(0).httpsPort(); return (httpsPort != null) ? httpsPort : 0; } return 0; } @Override public Set<String> customDomains() { Set<String> set = new HashSet<>(); for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } return Collections.unmodifiableSet(set); } @Override public void start() { this.parent().startEndpoint(this.name()); } @Override public Mono<Void> startAsync() { return this.parent().startEndpointAsync(this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return this.parent().stopEndpointAsync(this.name()); } @Override public void purgeContent(Set<String> contentPaths) { if (contentPaths != null) { this.purgeContentAsync(contentPaths).block(); } } @Override public Mono<Void> purgeContentAsync(Set<String> contentPaths) { return this.parent().purgeEndpointContentAsync(this.name(), contentPaths); } @Override public void loadContent(Set<String> contentPaths) { this.loadContentAsync(contentPaths).block(); } @Override public Mono<Void> loadContentAsync(Set<String> contentPaths) { return this.parent().loadEndpointContentAsync(this.name(), contentPaths); } @Override public CustomDomainValidationResult validateCustomDomain(String hostName) { return this.validateCustomDomainAsync(hostName).block(); } @Override public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) { return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName); } @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { this.innerModel().origins().add( new DeepCreatedOrigin() .withName(originName) .withHostname(hostname)); return this; } @Override public CdnEndpointImpl withOrigin(String hostname) { return this.withOrigin("origin", hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) { return this.withOrigin(originName, hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String hostname) { return this.withOrigin(hostname); } @Override public CdnEndpointImpl withOriginPath(String originPath) { this.innerModel().withOriginPath(originPath); return this; } @Override public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) { this.innerModel().withIsHttpAllowed(httpAllowed); return this; } @Override public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) { this.innerModel().withIsHttpsAllowed(httpsAllowed); return this; } @Override public CdnEndpointImpl withHttpPort(int httpPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpPort(httpPort); } return this; } @Override public CdnEndpointImpl withHttpsPort(int httpsPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpsPort(httpsPort); } return this; } @Override public CdnEndpointImpl withHostHeader(String hostHeader) { this.innerModel().withOriginHostHeader(hostHeader); return this; } @Override public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) { List<String> list = null; if (contentTypesToCompress != null) { list = new ArrayList<>(contentTypesToCompress); } this.innerModel().withContentTypesToCompress(list); return this; } @Override public CdnEndpointImpl withoutContentTypesToCompress() { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().clear(); } return this; } @Override public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() == null) { this.innerModel().withContentTypesToCompress(new ArrayList<>()); } this.innerModel().contentTypesToCompress().add(contentTypeToCompress); return this; } @Override public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().remove(contentTypeToCompress); } return this; } @Override public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) { this.innerModel().withIsCompressionEnabled(compressionEnabled); return this; } @Override public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) { this.innerModel().withQueryStringCachingBehavior(cachingBehavior); return this; } @Override public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) { List<GeoFilter> list = null; if (geoFilters != null) { list = new ArrayList<>(geoFilters); } this.innerModel().withGeoFilters(list); return this; } @Override public CdnEndpointImpl withoutGeoFilters() { if (this.innerModel().geoFilters() != null) { this.innerModel().geoFilters().clear(); } return this; } @Override public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } geoFilter.countryCodes().add(countryCode.toString()); this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withGeoFilter( String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } else { geoFilter.countryCodes().clear(); } for (CountryIsoCode countryCode : countryCodes) { geoFilter.countryCodes().add(countryCode.toString()); } this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withoutGeoFilter(String relativePath) { this.innerModel().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath)); return this; } @Override public CdnEndpointImpl withCustomDomain(String hostName) { this.customDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } @Override @SuppressWarnings("unchecked") public CdnStandardRulesEngineRuleImpl defineNewStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } CdnStandardRulesEngineRuleImpl deliveryRule = new CdnStandardRulesEngineRuleImpl(this, name); this.standardRulesEngineRuleMap.put(name, deliveryRule.innerModel()); return deliveryRule; } @Override @SuppressWarnings("unchecked") public CdnStandardRulesEngineRuleImpl updateStandardRulesEngineRule(String name) { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format("Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } return new CdnStandardRulesEngineRuleImpl(this, standardRulesEngineRules().get(name)); } @Override @Override public CdnEndpointImpl withoutCustomDomain(String hostName) { deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) { if (this.innerModel().geoFilters() == null) { this.innerModel().withGeoFilters(new ArrayList<>()); } GeoFilter geoFilter = null; for (GeoFilter filter : this.innerModel().geoFilters()) { if (filter.relativePath().equals(relativePath)) { geoFilter = filter; break; } } if (geoFilter == null) { geoFilter = new GeoFilter(); } else { this.innerModel().geoFilters().remove(geoFilter); } geoFilter.withRelativePath(relativePath) .withAction(action); return geoFilter; } private void initializeRuleMapForStandardMicrosoftSku() { standardRulesEngineRuleMap.clear(); if (isStandardMicrosoftSku() && innerModel().deliveryPolicy() != null && innerModel().deliveryPolicy().rules() != null) { for (DeliveryRule rule : innerModel().deliveryPolicy().rules()) { this.standardRulesEngineRuleMap.put(rule.name(), rule); } } } private boolean isStandardMicrosoftSku() { return SkuName.STANDARD_MICROSOFT.equals(parent().sku().name()); } }
class CdnEndpointImpl extends ExternalChildResourceImpl< CdnEndpoint, EndpointInner, CdnProfileImpl, CdnProfile> implements CdnEndpoint, CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>, CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>, CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>, CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>, CdnEndpoint.UpdateStandardEndpoint, CdnEndpoint.UpdatePremiumEndpoint { private List<CustomDomainInner> customDomainList; private List<CustomDomainInner> deletedCustomDomainList; private final Map<String, DeliveryRule> standardRulesEngineRuleMap = new HashMap<>(); CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) { super(name, parent, inner); this.customDomainList = new ArrayList<>(); this.deletedCustomDomainList = new ArrayList<>(); initializeRuleMapForStandardMicrosoftSku(); } @Override public String id() { return this.innerModel().id(); } @Override public Mono<CdnEndpoint> createResourceAsync() { final CdnEndpointImpl self = this; if (isStandardMicrosoftSku() && this.innerModel().deliveryPolicy() == null && this.standardRulesEngineRuleMap.size() > 0) { this.innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()))); } return this.parent().manager().serviceClient().getEndpoints().createAsync(this.parent().resourceGroupName(), this.parent().name(), this.name(), this.innerModel()) .flatMap(inner -> { self.setInner(inner); return Flux.fromIterable(self.customDomainList) .flatMapDelayError(customDomainInner -> self.parent().manager().serviceClient() .getCustomDomains().createAsync( self.parent().resourceGroupName(), self.parent().name(), self.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(customDomainInner.hostname())), 32, 32) .then(self.parent().manager().serviceClient() .getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name()) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; })); }); } @Override public Mono<CdnEndpoint> updateResourceAsync() { final CdnEndpointImpl self = this; EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters(); endpointUpdateParameters.withIsHttpAllowed(this.innerModel().isHttpAllowed()) .withIsHttpsAllowed(this.innerModel().isHttpsAllowed()) .withOriginPath(this.innerModel().originPath()) .withOriginHostHeader(this.innerModel().originHostHeader()) .withIsCompressionEnabled(this.innerModel().isCompressionEnabled()) .withContentTypesToCompress(this.innerModel().contentTypesToCompress()) .withGeoFilters(this.innerModel().geoFilters()) .withOptimizationType(this.innerModel().optimizationType()) .withQueryStringCachingBehavior(this.innerModel().queryStringCachingBehavior()) .withTags(this.innerModel().tags()); if (isStandardMicrosoftSku()) { List<DeliveryRule> rules = this.standardRulesEngineRuleMap.values() .stream() .sorted(Comparator.comparingInt(DeliveryRule::order)) .collect(Collectors.toList()); ensureDeliveryPolicy(); endpointUpdateParameters.withDeliveryPolicy( new EndpointPropertiesUpdateParametersDeliveryPolicy() .withRules(rules)); } DeepCreatedOrigin originInner = this.innerModel().origins().get(0); OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters() .withHostname(originInner.hostname()) .withHttpPort(originInner.httpPort()) .withHttpsPort(originInner.httpsPort()); Mono<EndpointInner> originUpdateTask = this.parent().manager().serviceClient().getOrigins().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), originInner.name(), originUpdateParameters) .then(Mono.empty()); Mono<EndpointInner> endpointUpdateTask = this.parent().manager().serviceClient().getEndpoints().updateAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), endpointUpdateParameters); Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList) .flatMapDelayError(itemToCreate -> this.parent().manager().serviceClient().getCustomDomains().createAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), self.parent().manager().resourceManager().internalContext() .randomResourceName("CustomDomain", 50), new CustomDomainParameters().withHostname(itemToCreate.hostname()) ), 32, 32); Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList) .flatMapDelayError(itemToDelete -> this.parent().manager().serviceClient().getCustomDomains().deleteAsync( this.parent().resourceGroupName(), this.parent().name(), this.name(), itemToDelete.name() ), 32, 32); Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask) .then(Mono.empty()); return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask) .last() .map(inner -> { self.setInner(inner); self.customDomainList.clear(); self.deletedCustomDomainList.clear(); return self; }); } @Override public Mono<Void> deleteResourceAsync() { return this.parent().manager().serviceClient().getEndpoints().deleteAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public Mono<CdnEndpoint> refreshAsync() { final CdnEndpointImpl self = this; return super.refreshAsync() .flatMap(cdnEndpoint -> { self.customDomainList.clear(); self.deletedCustomDomainList.clear(); initializeRuleMapForStandardMicrosoftSku(); return self.parent().manager().serviceClient().getCustomDomains().listByEndpointAsync( self.parent().resourceGroupName(), self.parent().name(), self.name() ) .collectList() .map(customDomainInners -> { self.customDomainList.addAll(customDomainInners); return self; }); }); } @Override protected Mono<EndpointInner> getInnerAsync() { return this.parent().manager().serviceClient().getEndpoints().getAsync(this.parent().resourceGroupName(), this.parent().name(), this.name()); } @Override public PagedIterable<ResourceUsage> listResourceUsage() { return PagedConverter.mapPage(this.parent().manager().serviceClient().getEndpoints().listResourceUsage( this.parent().resourceGroupName(), this.parent().name(), this.name()), ResourceUsage::new); } @Override public Map<String, DeliveryRule> standardRulesEngineRules() { return Collections.unmodifiableMap(this.standardRulesEngineRuleMap); } @Override public CdnProfileImpl attach() { return this.parent(); } @Override public String originHostHeader() { return this.innerModel().originHostHeader(); } @Override public String originPath() { return this.innerModel().originPath(); } @Override public Set<String> contentTypesToCompress() { List<String> contentTypes = this.innerModel().contentTypesToCompress(); Set<String> set = new HashSet<>(); if (contentTypes != null) { set.addAll(contentTypes); } return Collections.unmodifiableSet(set); } @Override public boolean isCompressionEnabled() { return this.innerModel().isCompressionEnabled(); } @Override public boolean isHttpAllowed() { return this.innerModel().isHttpAllowed(); } @Override public boolean isHttpsAllowed() { return this.innerModel().isHttpsAllowed(); } @Override public QueryStringCachingBehavior queryStringCachingBehavior() { return this.innerModel().queryStringCachingBehavior(); } @Override public String optimizationType() { if (this.innerModel().optimizationType() == null) { return null; } return this.innerModel().optimizationType().toString(); } @Override public List<GeoFilter> geoFilters() { return this.innerModel().geoFilters(); } @Override public String hostname() { return this.innerModel().hostname(); } @Override public EndpointResourceState resourceState() { return this.innerModel().resourceState(); } @Override public String provisioningState() { return this.innerModel().provisioningState() == null ? null : this.innerModel().provisioningState().toString(); } @Override public String originHostName() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { return this.innerModel().origins().get(0).hostname(); } return null; } @Override public int httpPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpPort = this.innerModel().origins().get(0).httpPort(); return (httpPort != null) ? httpPort : 0; } return 0; } @Override public int httpsPort() { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { Integer httpsPort = this.innerModel().origins().get(0).httpsPort(); return (httpsPort != null) ? httpsPort : 0; } return 0; } @Override public Set<String> customDomains() { Set<String> set = new HashSet<>(); for (CustomDomainInner customDomainInner : this.parent().manager().serviceClient().getCustomDomains() .listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) { set.add(customDomainInner.hostname()); } return Collections.unmodifiableSet(set); } @Override public void start() { this.parent().startEndpoint(this.name()); } @Override public Mono<Void> startAsync() { return this.parent().startEndpointAsync(this.name()); } @Override public void stop() { this.stopAsync().block(); } @Override public Mono<Void> stopAsync() { return this.parent().stopEndpointAsync(this.name()); } @Override public void purgeContent(Set<String> contentPaths) { if (contentPaths != null) { this.purgeContentAsync(contentPaths).block(); } } @Override public Mono<Void> purgeContentAsync(Set<String> contentPaths) { return this.parent().purgeEndpointContentAsync(this.name(), contentPaths); } @Override public void loadContent(Set<String> contentPaths) { this.loadContentAsync(contentPaths).block(); } @Override public Mono<Void> loadContentAsync(Set<String> contentPaths) { return this.parent().loadEndpointContentAsync(this.name(), contentPaths); } @Override public CustomDomainValidationResult validateCustomDomain(String hostName) { return this.validateCustomDomainAsync(hostName).block(); } @Override public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) { return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName); } @Override public CdnEndpointImpl withOrigin(String originName, String hostname) { this.innerModel().origins().add( new DeepCreatedOrigin() .withName(originName) .withHostname(hostname)); return this; } @Override public CdnEndpointImpl withOrigin(String hostname) { return this.withOrigin("origin", hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) { return this.withOrigin(originName, hostname); } @Override public CdnEndpointImpl withPremiumOrigin(String hostname) { return this.withOrigin(hostname); } @Override public CdnEndpointImpl withOriginPath(String originPath) { this.innerModel().withOriginPath(originPath); return this; } @Override public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) { this.innerModel().withIsHttpAllowed(httpAllowed); return this; } @Override public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) { this.innerModel().withIsHttpsAllowed(httpsAllowed); return this; } @Override public CdnEndpointImpl withHttpPort(int httpPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpPort(httpPort); } return this; } @Override public CdnEndpointImpl withHttpsPort(int httpsPort) { if (this.innerModel().origins() != null && !this.innerModel().origins().isEmpty()) { this.innerModel().origins().get(0).withHttpsPort(httpsPort); } return this; } @Override public CdnEndpointImpl withHostHeader(String hostHeader) { this.innerModel().withOriginHostHeader(hostHeader); return this; } @Override public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) { List<String> list = null; if (contentTypesToCompress != null) { list = new ArrayList<>(contentTypesToCompress); } this.innerModel().withContentTypesToCompress(list); return this; } @Override public CdnEndpointImpl withoutContentTypesToCompress() { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().clear(); } return this; } @Override public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() == null) { this.innerModel().withContentTypesToCompress(new ArrayList<>()); } this.innerModel().contentTypesToCompress().add(contentTypeToCompress); return this; } @Override public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) { if (this.innerModel().contentTypesToCompress() != null) { this.innerModel().contentTypesToCompress().remove(contentTypeToCompress); } return this; } @Override public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) { this.innerModel().withIsCompressionEnabled(compressionEnabled); return this; } @Override public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) { this.innerModel().withQueryStringCachingBehavior(cachingBehavior); return this; } @Override public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) { List<GeoFilter> list = null; if (geoFilters != null) { list = new ArrayList<>(geoFilters); } this.innerModel().withGeoFilters(list); return this; } @Override public CdnEndpointImpl withoutGeoFilters() { if (this.innerModel().geoFilters() != null) { this.innerModel().geoFilters().clear(); } return this; } @Override public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } geoFilter.countryCodes().add(countryCode.toString()); this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withGeoFilter( String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) { GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action); if (geoFilter.countryCodes() == null) { geoFilter.withCountryCodes(new ArrayList<>()); } else { geoFilter.countryCodes().clear(); } for (CountryIsoCode countryCode : countryCodes) { geoFilter.countryCodes().add(countryCode.toString()); } this.innerModel().geoFilters().add(geoFilter); return this; } @Override public CdnEndpointImpl withoutGeoFilter(String relativePath) { this.innerModel().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath)); return this; } @Override public CdnEndpointImpl withCustomDomain(String hostName) { this.customDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } @Override public CdnStandardRulesEngineRuleImpl defineNewStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); CdnStandardRulesEngineRuleImpl deliveryRule = new CdnStandardRulesEngineRuleImpl(this, name); this.standardRulesEngineRuleMap.put(name, deliveryRule.innerModel()); return deliveryRule; } @Override public CdnStandardRulesEngineRuleImpl updateStandardRulesEngineRule(String name) { throwIfNotStandardMicrosoftSku(); return new CdnStandardRulesEngineRuleImpl(this, standardRulesEngineRules().get(name)); } @Override @Override public CdnEndpointImpl withoutCustomDomain(String hostName) { deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName)); return this; } private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) { if (this.innerModel().geoFilters() == null) { this.innerModel().withGeoFilters(new ArrayList<>()); } GeoFilter geoFilter = null; for (GeoFilter filter : this.innerModel().geoFilters()) { if (filter.relativePath().equals(relativePath)) { geoFilter = filter; break; } } if (geoFilter == null) { geoFilter = new GeoFilter(); } else { this.innerModel().geoFilters().remove(geoFilter); } geoFilter.withRelativePath(relativePath) .withAction(action); return geoFilter; } private void initializeRuleMapForStandardMicrosoftSku() { standardRulesEngineRuleMap.clear(); if (isStandardMicrosoftSku() && innerModel().deliveryPolicy() != null && innerModel().deliveryPolicy().rules() != null) { for (DeliveryRule rule : innerModel().deliveryPolicy().rules()) { this.standardRulesEngineRuleMap.put(rule.name(), rule); } } } private boolean isStandardMicrosoftSku() { return SkuName.STANDARD_MICROSOFT.equals(parent().sku().name()); } private void throwIfNotStandardMicrosoftSku() { if (!isStandardMicrosoftSku()) { throw new IllegalStateException(String.format( "Standard rules engine only supports for Standard Microsoft SKU, " + "current SKU is %s", parent().sku().name())); } } private void ensureDeliveryPolicy() { if (innerModel().deliveryPolicy() == null) { innerModel().withDeliveryPolicy(new EndpointPropertiesUpdateParametersDeliveryPolicy()); } } }
Where is roomParticipantsMri being used? Clean up if not used
public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); List<String> roomParticipantsMri = new ArrayList<String>(); roomParticipantsMri.add(participants1.get(0).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(1).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(2).getCommunicationIdentifier().getRawId()); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
List<String> roomParticipantsMri = new ArrayList<String>();
public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); cleanUpUsers(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); Mono<UpsertParticipantsResult> addPartcipantResponse = roomsAsyncClient.upsertParticipants(roomId, participants5); StepVerifier.create(addPartcipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == firstParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<UpsertParticipantsResult> updateParticipantResponse = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants2); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants5); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participantsWithRoleUpdates); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participants9); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participants9); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants5); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(NONEXIST_ROOM_ID)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(NONEXIST_ROOM_ID)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); createUsers(httpClient); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
We should assert valid from, validuntil, createdAt, id are all not null.
public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
assertEquals(true, roomResult.getValidFrom() != null);
public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); cleanUpUsers(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); List<String> roomParticipantsMri = new ArrayList<String>(); roomParticipantsMri.add(participants1.get(0).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(1).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(2).getCommunicationIdentifier().getRawId()); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); Mono<UpsertParticipantsResult> addPartcipantResponse = roomsAsyncClient.upsertParticipants(roomId, participants5); StepVerifier.create(addPartcipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == firstParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<UpsertParticipantsResult> updateParticipantResponse = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants2); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants5); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participantsWithRoleUpdates); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participants9); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participants9); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants5); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(NONEXIST_ROOM_ID)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(NONEXIST_ROOM_ID)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); createUsers(httpClient); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
Why just validated validFrrom? We should validate all properties of the result
public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond());
public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); cleanUpUsers(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); List<String> roomParticipantsMri = new ArrayList<String>(); roomParticipantsMri.add(participants1.get(0).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(1).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(2).getCommunicationIdentifier().getRawId()); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); Mono<UpsertParticipantsResult> addPartcipantResponse = roomsAsyncClient.upsertParticipants(roomId, participants5); StepVerifier.create(addPartcipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == firstParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<UpsertParticipantsResult> updateParticipantResponse = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants2); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants5); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participantsWithRoleUpdates); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participants9); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participants9); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants5); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(NONEXIST_ROOM_ID)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(NONEXIST_ROOM_ID)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); createUsers(httpClient); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
Yeah, I think I added that to test something, removed now.
public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); List<String> roomParticipantsMri = new ArrayList<String>(); roomParticipantsMri.add(participants1.get(0).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(1).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(2).getCommunicationIdentifier().getRawId()); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
List<String> roomParticipantsMri = new ArrayList<String>();
public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); cleanUpUsers(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); Mono<UpsertParticipantsResult> addPartcipantResponse = roomsAsyncClient.upsertParticipants(roomId, participants5); StepVerifier.create(addPartcipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == firstParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<UpsertParticipantsResult> updateParticipantResponse = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants2); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants5); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participantsWithRoleUpdates); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participants9); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participants9); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants5); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(NONEXIST_ROOM_ID)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(NONEXIST_ROOM_ID)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); createUsers(httpClient); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
I thought doing an extra check really wouldn't change things since validUntil is only available when the whole room model is returned. But I have now added checks for all room properties.
public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond());
public void createRoomFullCycleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithOutResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = response1.block().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<CommunicationRoom> response3 = roomsAsyncClient.updateRoom(roomId, updateOptions); StepVerifier.create(response3) .assertNext(result3 -> { assertEquals(true, result3.getValidUntil().toEpochSecond() > VALID_FROM.toEpochSecond()); }).verifyComplete(); Mono<CommunicationRoom> response4 = roomsAsyncClient.getRoom(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertEquals(result4.getRoomId(), roomId); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); cleanUpUsers(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); List<String> roomParticipantsMri = new ArrayList<String>(); roomParticipantsMri.add(participants1.get(0).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(1).getCommunicationIdentifier().getRawId()); roomParticipantsMri.add(participants1.get(2).getCommunicationIdentifier().getRawId()); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsSyncWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getValidFrom() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); Mono<UpsertParticipantsResult> addPartcipantResponse = roomsAsyncClient.upsertParticipants(roomId, participants5); StepVerifier.create(addPartcipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == firstParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<UpsertParticipantsResult> updateParticipantResponse = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof UpsertParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants2); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants1); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, communicationIdentifiersForParticipants5); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participantsWithRoleUpdates); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participants9); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants8); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); Mono<Response<UpsertParticipantsResult>> response2 = roomsAsyncClient.upsertParticipantsWithResponse(roomId, participants9); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants5); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants2); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<UpsertParticipantsResult> response2 = roomsAsyncClient.upsertParticipants(roomId, participantsWithRoleUpdates); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(NONEXIST_ROOM_ID)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(NONEXIST_ROOM_ID)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); createUsers(httpClient); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
class RoomsAsyncClientTests extends RoomsTestBase { private RoomsAsyncClient roomsAsyncClient; private CommunicationIdentityClient communicationClient; private final String nonExistRoomId = "NotExistingRoomID"; @Override protected void beforeTest() { super.beforeTest(); } @Override protected void afterTest() { super.afterTest(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void createRoomFullCycleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "createRoomFullCycleWithResponse"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); UpdateRoomOptions updateOptions = new UpdateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_FROM.plusMonths(3)); Mono<Response<CommunicationRoom>> response3 = roomsAsyncClient.updateRoomWithResponse(roomId, updateOptions); System.out.println(VALID_FROM.plusMonths(3).getDayOfYear()); StepVerifier.create(response3) .assertNext(roomResult -> { assertHappyPath(roomResult, 200); }).verifyComplete(); Mono<Response<CommunicationRoom>> response4 = roomsAsyncClient.getRoomWithResponse(roomId); StepVerifier.create(response4) .assertNext(result4 -> { assertHappyPath(result4, 200); }).verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addUpdateAndRemoveParticipantsOperationsWithFullFlow(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addUpdateAndRemoveParticipantsOperationsWithFullFlow"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); StepVerifier.create(listParticipantsResponse2) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { if (participant.getCommunicationIdentifier().getRawId() == secondParticipant .getCommunicationIdentifier().getRawId()) { assertEquals(ParticipantRole.ATTENDEE, participant.getRole()); } }) .expectComplete() .verify(); RoomParticipant firstParticipantUpdated = new RoomParticipant(firstParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); RoomParticipant secondParticipantUpdated = new RoomParticipant(secondParticipant.getCommunicationIdentifier()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participantsToUpdate = Arrays.asList(firstParticipantUpdated, secondParticipantUpdated); Mono<AddOrUpdateParticipantsResult> updateParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participantsToUpdate); StepVerifier.create(updateParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof AddOrUpdateParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse3) .expectSubscription() .thenConsumeWhile(participant -> true, participant -> { assertEquals(ParticipantRole.CONSUMER, participant.getRole()); }) .expectComplete() .verify(); List<CommunicationIdentifier> participantsIdentifiersForParticipants = Arrays.asList( firstParticipant.getCommunicationIdentifier(), secondParticipant.getCommunicationIdentifier()); Mono<RemoveParticipantsResult> removeParticipantResponse = roomsAsyncClient.removeParticipants(roomId, participantsIdentifiersForParticipants); StepVerifier.create(removeParticipantResponse) .assertNext(result -> { assertEquals(true, result instanceof RemoveParticipantsResult); }) .verifyComplete(); PagedFlux<RoomParticipant> listParticipantsResponse4 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse4.count()) .expectNext(1L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void addParticipantsOperationWithOutResponse(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "addParticipantsOperationWithOutResponse"); assertNotNull(roomsAsyncClient); CreateRoomOptions createRoomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL); Mono<CommunicationRoom> createCommunicationRoom = roomsAsyncClient.createRoom(createRoomOptions); StepVerifier.create(createCommunicationRoom) .assertNext(roomResult -> { assertEquals(true, roomResult.getRoomId() != null); assertEquals(true, roomResult.getCreatedAt() != null); assertEquals(true, roomResult.getValidFrom() != null); assertEquals(true, roomResult.getValidUntil() != null); }).verifyComplete(); String roomId = createCommunicationRoom.block().getRoomId(); PagedFlux<RoomParticipant> listParticipantsResponse1 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse1.count()) .expectNext(0L) .verifyComplete(); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()).setRole(null); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); AddOrUpdateParticipantsResult addParticipantResponse = roomsAsyncClient.addOrUpdateParticipants(roomId, participants).block(); PagedFlux<RoomParticipant> listParticipantsResponse2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(listParticipantsResponse2.count()) .expectNext(3L) .verifyComplete(); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); Mono<RemoveParticipantsResult> response4 = roomsAsyncClient.removeParticipants(roomId, Arrays.asList(firstParticipant.getCommunicationIdentifier())); Mono<Response<Void>> response5 = roomsAsyncClient.deleteRoomWithResponse(roomId); StepVerifier.create(response5) .assertNext(result5 -> { assertEquals(result5.getStatusCode(), 204); }).verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void updateParticipantsToDefaultRoleWithResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "updateParticipantsToDefaultRoleWithResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); List<RoomParticipant> participants = Arrays.asList(firstParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<Response<CommunicationRoom>> response1 = roomsAsyncClient.createRoomWithResponse(roomOptions); StepVerifier.create(response1) .assertNext(roomResult -> { assertHappyPath(roomResult, 201); }) .verifyComplete(); String roomId = response1.block().getValue().getRoomId(); List<RoomParticipant> participantToUpdate = Arrays .asList(new RoomParticipant(firstParticipant.getCommunicationIdentifier())); Mono<Response<AddOrUpdateParticipantsResult>> response2 = roomsAsyncClient .addOrUpdateParticipantsWithResponse(roomId, participantToUpdate); StepVerifier.create(response2) .assertNext(result2 -> { assertEquals(result2.getStatusCode(), 200); }).verifyComplete(); PagedFlux<RoomParticipant> response3 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response3).assertNext(response4 -> { assertEquals(ParticipantRole.ATTENDEE, response4.getRole()); }) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void listParticipantsWithOutResponseStep(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "listParticipantsWithOutResponseStep"); assertNotNull(roomsAsyncClient); RoomParticipant firstParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant secondParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.PRESENTER); RoomParticipant thirdParticipant = new RoomParticipant(communicationClient.createUser()) .setRole(ParticipantRole.CONSUMER); List<RoomParticipant> participants = Arrays.asList(firstParticipant, secondParticipant, thirdParticipant); CreateRoomOptions roomOptions = new CreateRoomOptions() .setValidFrom(VALID_FROM) .setValidUntil(VALID_UNTIL) .setParticipants(participants); Mono<CommunicationRoom> response1 = roomsAsyncClient.createRoom(roomOptions); String roomId = response1.block().getRoomId(); PagedFlux<RoomParticipant> response2 = roomsAsyncClient.listParticipants(roomId); StepVerifier.create(response2.count()) .expectNext(3L) .verifyComplete(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void getRoomWithUnexistingRoomId(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "getRoomWithUnexistingRoomId"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.getRoom(nonExistRoomId)).verifyError(); } @ParameterizedTest @MethodSource("com.azure.core.test.TestBase public void deleteRoomWithConnectionString(HttpClient httpClient) { roomsAsyncClient = setupAsyncClient(httpClient, "deleteRoomWithConnectionString"); assertNotNull(roomsAsyncClient); StepVerifier.create(roomsAsyncClient.deleteRoomWithResponse(nonExistRoomId)).verifyError(); } private RoomsAsyncClient setupAsyncClient(HttpClient httpClient, String testName) { RoomsClientBuilder builder = getRoomsClientWithConnectionString(httpClient, RoomsServiceVersion.V2023_03_31_PREVIEW); communicationClient = getCommunicationIdentityClientBuilder(httpClient).buildClient(); return addLoggingPolicy(builder, testName).buildAsyncClient(); } }
These could be done with a Swagger transform and adding `x-ms-client` name to the Swagger definition for these properties.
private void customizeSnapshot(ClassCustomization classCustomization) { classCustomization.getProperty("created").rename("createdAt"); classCustomization.getProperty("expires").rename("expiresAt"); classCustomization.getProperty("itemsCount").rename("itemCount"); classCustomization.getMethod("getRetentionPeriod") .setReturnType("Duration", "") .replaceBody(joinWithNewline( "if (this.retentionPeriod == null) {", " return null;", "}", "return Duration.ofSeconds(this.retentionPeriod);" ), Arrays.asList("java.time.Duration")); classCustomization.getMethod("setRetentionPeriod") .replaceParameters("Duration retentionPeriod") .replaceBody(joinWithNewline( "this.retentionPeriod = retentionPeriod == null ? null : retentionPeriod.getSeconds();", "return this;" )); classCustomization.getConstructor("ConfigurationSettingSnapshot") .removeAnnotation("JsonCreator"); }
classCustomization.getProperty("itemsCount").rename("itemCount");
private void customizeSnapshot(ClassCustomization classCustomization) { classCustomization.getMethod("getRetentionPeriod") .setReturnType("Duration", "") .replaceBody(joinWithNewline( "if (this.retentionPeriod == null) {", " return null;", "}", "return Duration.ofSeconds(this.retentionPeriod);" ), Arrays.asList("java.time.Duration")); classCustomization.getMethod("setRetentionPeriod") .replaceParameters("Duration retentionPeriod") .replaceBody(joinWithNewline( "this.retentionPeriod = retentionPeriod == null ? null : retentionPeriod.getSeconds();", "return this;" )); }
class AppConfigCustomization extends Customization { @Override public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models"); customizeKeyValueFilter(models.getClass("SnapshotSettingFilter")); customizeKeyValueFields(models.getClass("SettingFields")); customizeSnapshot(models.getClass("ConfigurationSettingSnapshot")); } private void customizeKeyValueFilter(ClassCustomization classCustomization) { classCustomization.getMethod("setLabel") .getJavadoc() .setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field."); classCustomization.getMethod("getKey") .getJavadoc() .setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field."); classCustomization.getMethod("getLabel") .getJavadoc() .setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field."); classCustomization.getConstructor("SnapshotSettingFilter") .removeAnnotation("JsonCreator"); } private void customizeKeyValueFields(ClassCustomization classCustomization) { classCustomization.addImports("java.util.Locale;"); classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;"); MethodCustomization fromString = classCustomization.getMethod("fromString"); fromString.getJavadoc() .setDescription("Creates or finds a {@link SettingFields} from its string representation.") .setReturn("the corresponding {@link SettingFields}"); fromString.removeAnnotation("JsonCreator"); classCustomization.getJavadoc() .setDescription(joinWithNewline( "", "Fields in {@link ConfigurationSetting} that can be returned from GET queries.", "", "@see SettingSelector", "@see ConfigurationAsyncClient", "" )); addToStringMapper(classCustomization); } private ClassCustomization addToStringMapper(ClassCustomization classCustomization) { return classCustomization.customizeAst(ast -> { ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get(); clazz.removeJavaDocComment(); clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String") .addParameter("SettingFields", "field") .setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);")))) .addAnnotation(Deprecated.class) .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( " * Converts the SettingFields to a string that is usable for HTTP requests and logging.", " * @param field SettingFields to map.", " * @return SettingFields as a lowercase string in the US locale.", " * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests." ))); }); } private static String joinWithNewline(String... lines) { return String.join("\n", lines); } }
class AppConfigCustomization extends Customization { @Override public void customize(LibraryCustomization customization, Logger logger) { PackageCustomization models = customization.getPackage("com.azure.data.appconfiguration.models"); customizeKeyValueFilter(models.getClass("SnapshotSettingFilter")); customizeKeyValueFields(models.getClass("SettingFields")); customizeSnapshot(models.getClass("ConfigurationSettingSnapshot")); } private void customizeKeyValueFilter(ClassCustomization classCustomization) { classCustomization.getMethod("setLabel") .getJavadoc() .setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field."); classCustomization.getMethod("getKey") .getJavadoc() .setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field."); classCustomization.getMethod("getLabel") .getJavadoc() .setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field."); } private void customizeKeyValueFields(ClassCustomization classCustomization) { classCustomization.addImports("java.util.Locale;"); classCustomization.addImports("com.azure.data.appconfiguration.ConfigurationAsyncClient;"); MethodCustomization fromString = classCustomization.getMethod("fromString"); fromString.getJavadoc() .setDescription("Creates or finds a {@link SettingFields} from its string representation.") .setReturn("the corresponding {@link SettingFields}"); fromString.removeAnnotation("JsonCreator"); classCustomization.getJavadoc() .setDescription(joinWithNewline( "", "Fields in {@link ConfigurationSetting} that can be returned from GET queries.", "", "@see SettingSelector", "@see ConfigurationAsyncClient", "" )); addToStringMapper(classCustomization); } private ClassCustomization addToStringMapper(ClassCustomization classCustomization) { return classCustomization.customizeAst(ast -> { ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get(); clazz.removeJavaDocComment(); clazz.addMethod("toStringMapper", Modifier.Keyword.STATIC, Modifier.Keyword.PUBLIC).setType("String") .addParameter("SettingFields", "field") .setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return field.toString().toLowerCase(Locale.US);")))) .addAnnotation(Deprecated.class) .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( " * Converts the SettingFields to a string that is usable for HTTP requests and logging.", " * @param field SettingFields to map.", " * @return SettingFields as a lowercase string in the US locale.", " * @deprecated This method is no longer needed. SettingFields is using lower case enum value for the HTTP requests." ))); }); } private static String joinWithNewline(String... lines) { return String.join("\n", lines); } }
```suggestion // BEGIN: com.azure.identity.credential.workloadidentitycredential.construct TokenCredential onBehalfOfCredential = new WorkloadIdentityCredentialBuilder() .clientId("<clientID>") .tenantId("<tenantID>") .tokenFilePath("<token-file-path>") .build(); // END: com.azure.identity.credential.workloadidentitycredential.construct ```
public void authorizationCodeCredentialsCodeSnippets() { TokenCredential authorizationCodeCredential = new AuthorizationCodeCredentialBuilder() .authorizationCode("{authorization-code-received-at-redirectURL}") .redirectUrl("{redirectUrl-where-authorization-code-is-received}") .clientId("{clientId-of-application-being-authenticated") .build(); } /** * Method to insert code snippets for {@link OnBehalfOfCredential} */ public void oboCredentialsCodeSnippets() { TokenCredential onBehalfOfCredential = new OnBehalfOfCredentialBuilder() .clientId("<app-client-ID>") .clientSecret("<app-Client-Secret>") .userAssertion("<user-assertion>") .build(); } /** * Method to insert code snippets for {@link WorkloadIdentityCredential} */ public void workloadIdentityCredentialCodeSnippets() { TokenCredential onBehalfOfCredential = new WorkloadIdentityCredentialBuilder() .clientId("<clientID>") .tenantId("<tenantID>") .tokenFilePath("<token-file-path>") .build(); } /** * Method to insert code snippets for {@link AzureDeveloperCliCredential} */ public void azureDeveloperCliCredentialCodeSnippets() { TokenCredential azureDevCliCredential = new AzureDeveloperCliCredentialBuilder() .build(); } }
public void authorizationCodeCredentialsCodeSnippets() { TokenCredential authorizationCodeCredential = new AuthorizationCodeCredentialBuilder() .authorizationCode("{authorization-code-received-at-redirectURL}") .redirectUrl("{redirectUrl-where-authorization-code-is-received}") .clientId("{clientId-of-application-being-authenticated") .build(); } /** * Method to insert code snippets for {@link OnBehalfOfCredential} */ public void oboCredentialsCodeSnippets() { TokenCredential onBehalfOfCredential = new OnBehalfOfCredentialBuilder() .clientId("<app-client-ID>") .clientSecret("<app-Client-Secret>") .userAssertion("<user-assertion>") .build(); } /** * Method to insert code snippets for {@link WorkloadIdentityCredential} */ public void workloadIdentityCredentialCodeSnippets() { TokenCredential onBehalfOfCredential = new WorkloadIdentityCredentialBuilder() .clientId("<clientID>") .tenantId("<tenantID>") .tokenFilePath("<token-file-path>") .build(); } /** * Method to insert code snippets for {@link AzureDeveloperCliCredential} */ public void azureDeveloperCliCredentialCodeSnippets() { TokenCredential azureDevCliCredential = new AzureDeveloperCliCredentialBuilder() .build(); } }
class JavaDocCodeSnippets { private String tenantId = System.getenv("AZURE_TENANT_ID"); private String clientId = System.getenv("AZURE_CLIENT_ID"); private String clientSecret = System.getenv("AZURE_CLIENT_SECRET"); private String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; private String fakePasswordPlaceholder = "fakePasswordPlaceholder"; /** * Method to insert code snippets for {@link ClientSecretCredential} */ public void clientSecretCredentialCodeSnippets() { TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build(); TokenCredential secretCredential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ClientCertificateCredential} */ public void clientCertificateCredentialCodeSnippets() { TokenCredential clientCertificateCredential = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate("<PATH-TO-PEM-CERTIFICATE>") .build(); TokenCredential certificateCredential = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pfxCertificate("<PATH-TO-PFX-CERTIFICATE>", "P@s$w0rd") .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ClientAssertionCredential} */ public void clientAssertionCredentialCodeSnippets() { TokenCredential clientAssertionCredential = new ClientAssertionCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientAssertion(() -> "<Client-Assertion>") .build(); TokenCredential assertionCredential = new ClientAssertionCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientAssertion(() -> "<Client-Assertion>") .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ChainedTokenCredential} */ public void chainedTokenCredentialCodeSnippets() { TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder() .clientId(clientId) .username(fakeUsernamePlaceholder) .password(fakePasswordPlaceholder) .build(); TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder() .clientId(clientId) .port(8765) .build(); TokenCredential credential = new ChainedTokenCredentialBuilder() .addLast(usernamePasswordCredential) .addLast(interactiveBrowserCredential) .build(); } /** * Method to insert code snippets for {@link DefaultAzureCredential} */ public void defaultAzureCredentialCodeSnippets() { TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder() .build(); TokenCredential dacWithUserAssignedManagedIdentity = new DefaultAzureCredentialBuilder() .managedIdentityClientId("<Managed-Identity-Client-Id") .build(); } /** * Method to insert code snippets for {@link InteractiveBrowserCredential} */ public void interactiveBrowserCredentialsCodeSnippets() { TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder() .redirectUrl("http: .build(); } /** * Method to insert code snippets for {@link ManagedIdentityCredential} */ public void managedIdentityCredentialsCodeSnippets() { TokenCredential managedIdentityCredentialUserAssigned = new ManagedIdentityCredentialBuilder() .clientId(clientId) .build(); TokenCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link EnvironmentCredential} */ public void environmentCredentialsCodeSnippets() { TokenCredential environmentCredential = new EnvironmentCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link AzureCliCredential} */ public void azureCliCredentialsCodeSnippets() { TokenCredential azureCliCredential = new AzureCliCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link IntelliJCredential} */ public void intelliJCredentialsCodeSnippets() { TokenCredential intelliJCredential = new IntelliJCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link DeviceCodeCredential} */ public void deviceCodeCredentialsCodeSnippets() { TokenCredential deviceCodeCredential = new DeviceCodeCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link UsernamePasswordCredential} */ public void usernamePasswordCredentialsCodeSnippets() { TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder() .clientId("<your app client ID>") .username("<your username>") .password("<your password>") .build(); } /** * Method to insert code snippets for {@link AzurePowerShellCredential} */ public void azurePowershellCredentialsCodeSnippets() { TokenCredential powerShellCredential = new AzurePowerShellCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link AuthorizationCodeCredential} */
class JavaDocCodeSnippets { private String tenantId = System.getenv("AZURE_TENANT_ID"); private String clientId = System.getenv("AZURE_CLIENT_ID"); private String clientSecret = System.getenv("AZURE_CLIENT_SECRET"); private String fakeUsernamePlaceholder = "fakeUsernamePlaceholder"; private String fakePasswordPlaceholder = "fakePasswordPlaceholder"; /** * Method to insert code snippets for {@link ClientSecretCredential} */ public void clientSecretCredentialCodeSnippets() { TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .build(); TokenCredential secretCredential = new ClientSecretCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientSecret(clientSecret) .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ClientCertificateCredential} */ public void clientCertificateCredentialCodeSnippets() { TokenCredential clientCertificateCredential = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate("<PATH-TO-PEM-CERTIFICATE>") .build(); TokenCredential certificateCredential = new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pfxCertificate("<PATH-TO-PFX-CERTIFICATE>", "P@s$w0rd") .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ClientAssertionCredential} */ public void clientAssertionCredentialCodeSnippets() { TokenCredential clientAssertionCredential = new ClientAssertionCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientAssertion(() -> "<Client-Assertion>") .build(); TokenCredential assertionCredential = new ClientAssertionCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .clientAssertion(() -> "<Client-Assertion>") .proxyOptions(new ProxyOptions(Type.HTTP, new InetSocketAddress("10.21.32.43", 5465))) .build(); } /** * Method to insert code snippets for {@link ChainedTokenCredential} */ public void chainedTokenCredentialCodeSnippets() { TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder() .clientId(clientId) .username(fakeUsernamePlaceholder) .password(fakePasswordPlaceholder) .build(); TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder() .clientId(clientId) .port(8765) .build(); TokenCredential credential = new ChainedTokenCredentialBuilder() .addLast(usernamePasswordCredential) .addLast(interactiveBrowserCredential) .build(); } /** * Method to insert code snippets for {@link DefaultAzureCredential} */ public void defaultAzureCredentialCodeSnippets() { TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder() .build(); TokenCredential dacWithUserAssignedManagedIdentity = new DefaultAzureCredentialBuilder() .managedIdentityClientId("<Managed-Identity-Client-Id") .build(); } /** * Method to insert code snippets for {@link InteractiveBrowserCredential} */ public void interactiveBrowserCredentialsCodeSnippets() { TokenCredential interactiveBrowserCredential = new InteractiveBrowserCredentialBuilder() .redirectUrl("http: .build(); } /** * Method to insert code snippets for {@link ManagedIdentityCredential} */ public void managedIdentityCredentialsCodeSnippets() { TokenCredential managedIdentityCredentialUserAssigned = new ManagedIdentityCredentialBuilder() .clientId(clientId) .build(); TokenCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link EnvironmentCredential} */ public void environmentCredentialsCodeSnippets() { TokenCredential environmentCredential = new EnvironmentCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link AzureCliCredential} */ public void azureCliCredentialsCodeSnippets() { TokenCredential azureCliCredential = new AzureCliCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link IntelliJCredential} */ public void intelliJCredentialsCodeSnippets() { TokenCredential intelliJCredential = new IntelliJCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link DeviceCodeCredential} */ public void deviceCodeCredentialsCodeSnippets() { TokenCredential deviceCodeCredential = new DeviceCodeCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link UsernamePasswordCredential} */ public void usernamePasswordCredentialsCodeSnippets() { TokenCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder() .clientId("<your app client ID>") .username("<your username>") .password("<your password>") .build(); } /** * Method to insert code snippets for {@link AzurePowerShellCredential} */ public void azurePowershellCredentialsCodeSnippets() { TokenCredential powerShellCredential = new AzurePowerShellCredentialBuilder() .build(); } /** * Method to insert code snippets for {@link AuthorizationCodeCredential} */
can we use static logger instead?
public static TableItem createItem(TableResponseProperties properties) { if (creator == null) { try { Class.forName(TableItem.class.getName(), true, TableItemAccessHelper.class.getClassLoader()); } catch (ReflectiveOperationException ex) { throw new ClientLogger(TableItemAccessHelper.class).logExceptionAsError( new IllegalStateException("Failed to load 'TableItem' class within 'TableItemAccessHelper'.")); } } assert creator != null; return creator.apply(properties); }
throw new ClientLogger(TableItemAccessHelper.class).logExceptionAsError(
public static TableItem createItem(TableResponseProperties properties) { if (creator == null) { try { Class.forName(TableItem.class.getName(), true, TableItemAccessHelper.class.getClassLoader()); } catch (ReflectiveOperationException ex) { throw new ClientLogger(TableItemAccessHelper.class).logExceptionAsError( new IllegalStateException("Failed to load 'TableItem' class within 'TableItemAccessHelper'.", ex)); } } assert creator != null; return creator.apply(properties); }
class TableItemAccessHelper { private static Function<TableResponseProperties, TableItem> creator; /** * Sets the {@link TableItem} creator. * * @param creator The {@link TableItem} creator. */ public static void setTableItemCreator(Function<TableResponseProperties, TableItem> creator) { TableItemAccessHelper.creator = creator; } /** * Creates a {@link TableItem}. * * @param properties The {@link TableResponseProperties} used to construct the table. * @return The created {@link TableItem}. */ private TableItemAccessHelper() { } }
class TableItemAccessHelper { private static Function<TableResponseProperties, TableItem> creator; /** * Sets the {@link TableItem} creator. * * @param creator The {@link TableItem} creator. */ public static void setTableItemCreator(Function<TableResponseProperties, TableItem> creator) { TableItemAccessHelper.creator = creator; } /** * Creates a {@link TableItem}. * * @param properties The {@link TableResponseProperties} used to construct the table. * @return The created {@link TableItem}. */ private TableItemAccessHelper() { } }
I'd rather stick with this as if this path is reached this will likely end the process, or at least result in whatever happens next to not work, and this defers the creation of `ClientLogger` to when it is needed instead of eagerly being initialized in the clinit.
public static TableItem createItem(TableResponseProperties properties) { if (creator == null) { try { Class.forName(TableItem.class.getName(), true, TableItemAccessHelper.class.getClassLoader()); } catch (ReflectiveOperationException ex) { throw new ClientLogger(TableItemAccessHelper.class).logExceptionAsError( new IllegalStateException("Failed to load 'TableItem' class within 'TableItemAccessHelper'.")); } } assert creator != null; return creator.apply(properties); }
throw new ClientLogger(TableItemAccessHelper.class).logExceptionAsError(
public static TableItem createItem(TableResponseProperties properties) { if (creator == null) { try { Class.forName(TableItem.class.getName(), true, TableItemAccessHelper.class.getClassLoader()); } catch (ReflectiveOperationException ex) { throw new ClientLogger(TableItemAccessHelper.class).logExceptionAsError( new IllegalStateException("Failed to load 'TableItem' class within 'TableItemAccessHelper'.", ex)); } } assert creator != null; return creator.apply(properties); }
class TableItemAccessHelper { private static Function<TableResponseProperties, TableItem> creator; /** * Sets the {@link TableItem} creator. * * @param creator The {@link TableItem} creator. */ public static void setTableItemCreator(Function<TableResponseProperties, TableItem> creator) { TableItemAccessHelper.creator = creator; } /** * Creates a {@link TableItem}. * * @param properties The {@link TableResponseProperties} used to construct the table. * @return The created {@link TableItem}. */ private TableItemAccessHelper() { } }
class TableItemAccessHelper { private static Function<TableResponseProperties, TableItem> creator; /** * Sets the {@link TableItem} creator. * * @param creator The {@link TableItem} creator. */ public static void setTableItemCreator(Function<TableResponseProperties, TableItem> creator) { TableItemAccessHelper.creator = creator; } /** * Creates a {@link TableItem}. * * @param properties The {@link TableResponseProperties} used to construct the table. * @return The created {@link TableItem}. */ private TableItemAccessHelper() { } }
you can do `isHnsEnabled == Boolean.TRUE`
public StorageAccountInfo(final SkuName skuName, final AccountKind accountKind, Boolean isHnsEnabled) { this.skuName = skuName; this.accountKind = accountKind; this.isHnsEnabled = isHnsEnabled != null && isHnsEnabled; }
this.isHnsEnabled = isHnsEnabled != null && isHnsEnabled;
public StorageAccountInfo(final SkuName skuName, final AccountKind accountKind, Boolean isHnsEnabled) { this.skuName = skuName; this.accountKind = accountKind; this.isHnsEnabled = isHnsEnabled != null && isHnsEnabled; }
class StorageAccountInfo { private final SkuName skuName; private final AccountKind accountKind; private final boolean isHnsEnabled; /** * Constructs a {@link StorageAccountInfo}. * * @param skuName SKU of the account. * @param accountKind Type of the account. */ public StorageAccountInfo(final SkuName skuName, final AccountKind accountKind) { this.skuName = skuName; this.accountKind = accountKind; this.isHnsEnabled = false; } /** * Constructs a {@link StorageAccountInfo}. * * @param skuName SKU of the account. * @param accountKind Type of the account. * @param isHnsEnabled whether hierarchical namespace is enabled on the account. */ /** * Gets the SKU of the account. * * @return the SKU of the account. */ public SkuName getSkuName() { return skuName; } /** * Gets the information of the type of the account. * * @return the type of the account. */ public AccountKind getAccountKind() { return accountKind; } /** * Specifies whether hierarchical namespace is enabled on the account. * * @return whether hierarchical namespace is enabled on the account. */ public boolean isHierarchicalNamespaceEnabled() { return isHnsEnabled; } }
class StorageAccountInfo { private final SkuName skuName; private final AccountKind accountKind; private final boolean isHnsEnabled; /** * Constructs a {@link StorageAccountInfo}. * * @param skuName SKU of the account. * @param accountKind Type of the account. */ public StorageAccountInfo(final SkuName skuName, final AccountKind accountKind) { this.skuName = skuName; this.accountKind = accountKind; this.isHnsEnabled = false; } /** * Constructs a {@link StorageAccountInfo}. * * @param skuName SKU of the account. * @param accountKind Type of the account. * @param isHnsEnabled whether hierarchical namespace is enabled on the account. */ /** * Gets the SKU of the account. * * @return the SKU of the account. */ public SkuName getSkuName() { return skuName; } /** * Gets the information of the type of the account. * * @return the type of the account. */ public AccountKind getAccountKind() { return accountKind; } /** * Specifies whether hierarchical namespace is enabled on the account. * * @return whether hierarchical namespace is enabled on the account. */ public boolean isHierarchicalNamespaceEnabled() { return isHnsEnabled; } }
Tried doing this but had to revert changes since it caused linting errors in our pipelines. Thanks for the suggestion though :)
public StorageAccountInfo(final SkuName skuName, final AccountKind accountKind, Boolean isHnsEnabled) { this.skuName = skuName; this.accountKind = accountKind; this.isHnsEnabled = isHnsEnabled != null && isHnsEnabled; }
this.isHnsEnabled = isHnsEnabled != null && isHnsEnabled;
public StorageAccountInfo(final SkuName skuName, final AccountKind accountKind, Boolean isHnsEnabled) { this.skuName = skuName; this.accountKind = accountKind; this.isHnsEnabled = isHnsEnabled != null && isHnsEnabled; }
class StorageAccountInfo { private final SkuName skuName; private final AccountKind accountKind; private final boolean isHnsEnabled; /** * Constructs a {@link StorageAccountInfo}. * * @param skuName SKU of the account. * @param accountKind Type of the account. */ public StorageAccountInfo(final SkuName skuName, final AccountKind accountKind) { this.skuName = skuName; this.accountKind = accountKind; this.isHnsEnabled = false; } /** * Constructs a {@link StorageAccountInfo}. * * @param skuName SKU of the account. * @param accountKind Type of the account. * @param isHnsEnabled whether hierarchical namespace is enabled on the account. */ /** * Gets the SKU of the account. * * @return the SKU of the account. */ public SkuName getSkuName() { return skuName; } /** * Gets the information of the type of the account. * * @return the type of the account. */ public AccountKind getAccountKind() { return accountKind; } /** * Specifies whether hierarchical namespace is enabled on the account. * * @return whether hierarchical namespace is enabled on the account. */ public boolean isHierarchicalNamespaceEnabled() { return isHnsEnabled; } }
class StorageAccountInfo { private final SkuName skuName; private final AccountKind accountKind; private final boolean isHnsEnabled; /** * Constructs a {@link StorageAccountInfo}. * * @param skuName SKU of the account. * @param accountKind Type of the account. */ public StorageAccountInfo(final SkuName skuName, final AccountKind accountKind) { this.skuName = skuName; this.accountKind = accountKind; this.isHnsEnabled = false; } /** * Constructs a {@link StorageAccountInfo}. * * @param skuName SKU of the account. * @param accountKind Type of the account. * @param isHnsEnabled whether hierarchical namespace is enabled on the account. */ /** * Gets the SKU of the account. * * @return the SKU of the account. */ public SkuName getSkuName() { return skuName; } /** * Gets the information of the type of the account. * * @return the type of the account. */ public AccountKind getAccountKind() { return accountKind; } /** * Specifies whether hierarchical namespace is enabled on the account. * * @return whether hierarchical namespace is enabled on the account. */ public boolean isHierarchicalNamespaceEnabled() { return isHnsEnabled; } }
"Authorization" was this still needed to be excluded after MockTokenCredential?
HttpPipeline getPipeline(HttpClient httpClient, boolean forCleanup) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("token", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode() && !forCleanup) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization")));
HttpPipeline getPipeline(HttpClient httpClient, boolean forCleanup) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("token", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode() && !forCleanup) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class KeyVaultAdministrationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; protected static final boolean IS_MANAGED_HSM_DEPLOYED = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; static final String DISPLAY_NAME = "{displayName}"; @Override protected void beforeTest() { super.beforeTest(); Assumptions.assumeTrue(IS_MANAGED_HSM_DEPLOYED || getTestMode() == TestMode.PLAYBACK); KeyVaultCredentialPolicy.clearCache(); } @Override protected String getTestName() { return ""; } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } /** * Returns a stream of arguments that includes all eligible {@link HttpClient HttpClients}. * * @return A stream of {@link HttpClient HTTP clients} to test. */ static Stream<Arguments> createHttpClients() { return TestBase.getHttpClients().map(Arguments::of); } }
class KeyVaultAdministrationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; protected static final boolean IS_MANAGED_HSM_DEPLOYED = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; static final String DISPLAY_NAME = "{displayName}"; @Override protected void beforeTest() { super.beforeTest(); Assumptions.assumeTrue(IS_MANAGED_HSM_DEPLOYED || getTestMode() == TestMode.PLAYBACK); KeyVaultCredentialPolicy.clearCache(); } @Override protected String getTestName() { return ""; } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } /** * Returns a stream of arguments that includes all eligible {@link HttpClient HttpClients}. * * @return A stream of {@link HttpClient HTTP clients} to test. */ static Stream<Arguments> createHttpClients() { return TestBase.getHttpClients().map(Arguments::of); } }
We don't need this for the admin client Tests?
void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); }
KeyVaultCredentialPolicy.clearCache();
void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); }
class CertificateClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS); private static final String AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL = "ALL"; private static final String TEST_CERTIFICATE_NAME = "testCert"; @Override protected String getTestName() { return ""; } HttpPipeline getHttpPipeline(HttpClient httpClient) { return getHttpPipeline(httpClient, null); } HttpPipeline getHttpPipeline(HttpClient httpClient, String testTenantId) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("value", "-----BEGIN PRIVATE KEY-----\\n(.+\\n)*-----END PRIVATE KEY-----\\n", "-----BEGIN PRIVATE KEY-----\\nREDACTED\\n-----END PRIVATE KEY-----\\n", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); } @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createCertificateRunner(Consumer<CertificatePolicy> testRunner) { final CertificatePolicy certificatePolicy = CertificatePolicy.getDefault(); testRunner.accept(certificatePolicy); } @Test public abstract void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateDisabledCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateSpecificVersionRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getDeletedCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void recoverDeletedKeyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void backupCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void restoreCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void cancelCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listPropertiesOfCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listPropertiesOfCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateIssuersRunner(Consumer<HashMap<String, CertificateIssuer>> testRunner) { HashMap<String, CertificateIssuer> certificateIssuers = new HashMap<>(); String certificateIssuerName; for (int i = 0; i < 10; i++) { certificateIssuerName = testResourceNamer.randomName("listCertIssuer", 25); certificateIssuers.put(certificateIssuerName, setupIssuer(certificateIssuerName)); } testRunner.accept(certificateIssuers); } void updateIssuerRunner(BiConsumer<CertificateIssuer, CertificateIssuer> testRunner) { String issuerName = testResourceNamer.randomName("testIssuer", 25); final CertificateIssuer certificateIssuer = setupIssuer(issuerName); final CertificateIssuer issuerForUpdate = new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("otherFirst") .setLastName("otherLast") .setEmail("otherFirst.otherLast@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("otherIssuerAccountId") .setEnabled(false) .setOrganizationId("otherOrgId") .setPassword("fakePasswordPlaceholder"); testRunner.accept(certificateIssuer, issuerForUpdate); } @Test public abstract void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateOperationNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); CertificateContact setupContact() { return new CertificateContact() .setName("name") .setEmail("first.last@gmail.com") .setPhone("000-000-0000"); } Boolean validateContact(CertificateContact expected, CertificateContact actual) { return expected.getEmail().equals(actual.getEmail()) && expected.getName().equals(actual.getName()) && expected.getPhone().equals(actual.getPhone()); } @Test public abstract void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateVersionsRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName = testResourceNamer.randomName("listCertVersion", 25); for (int i = 1; i < 5; i++) { certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listDeletedCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 3; i++) { certificateName = testResourceNamer.randomName("listDeletedCert", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void importCertificateRunner(Consumer<ImportCertificateOptions> testRunner) { String certificatePassword = "fakePasswordPlaceholder"; String certificateName = testResourceNamer.randomName("importCertPkcs", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, Base64.getDecoder().decode(FAKE_CERTIFICATE_CONTENT)) .setPassword(certificatePassword) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = testResourceNamer.randomName("importCertPem", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); StringBuilder pemCert = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(pemPath))) { String line; while ((line = br.readLine()) != null) { pemCert.append(line).append("\n"); } } return pemCert.toString().getBytes(); } @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") CertificateIssuer setupIssuer(String issuerName) { return new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("first") .setLastName("last") .setEmail("first.last@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("issuerAccountId") .setEnabled(true) .setOrganizationId("orgId") .setPassword("fakePasswordPlaceholder"); } String toHexString(byte[] x5t) { if (x5t == null) { return ""; } StringBuilder hexString = new StringBuilder(); for (byte b : x5t) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString().replace("-", ""); } X509Certificate loadCerToX509Certificate(KeyVaultCertificateWithPolicy certificate) throws CertificateException, IOException { assertNotNull(certificate.getCer()); ByteArrayInputStream cerStream = new ByteArrayInputStream(certificate.getCer()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); cerStream.close(); return x509Certificate; } boolean issuerCreatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return expected.getAccountId().equals(actual.getAccountId()) && expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } boolean issuerUpdatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return !expected.getAccountId().equals(actual.getAccountId()) && !expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && !expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } CertificatePolicy setupPolicy() { return new CertificatePolicy(WellKnownIssuerNames.SELF, "CN=default") .setKeyUsage(CertificateKeyUsage.KEY_CERT_SIGN, CertificateKeyUsage.KEY_AGREEMENT) .setContentType(CertificateContentType.PKCS12) .setExportable(true) .setKeyType(CertificateKeyType.EC) .setCertificateTransparent(false) .setEnabled(true) .setKeyCurveName(CertificateKeyCurveName.P_384) .setKeyReusable(true) .setValidityInMonths(24) .setLifetimeActions(new LifetimeAction(CertificatePolicyAction.AUTO_RENEW).setDaysBeforeExpiry(40)); } boolean validatePolicy(CertificatePolicy expected, CertificatePolicy actual) { return expected.getKeyType().equals(actual.getKeyType()) && expected.getContentType().equals(actual.getContentType()) && actual.getCreatedOn() != null && expected.getIssuerName().equals(actual.getIssuerName()) && expected.getKeyCurveName().equals(actual.getKeyCurveName()) && expected.isExportable().equals(actual.isExportable()) && expected.isCertificateTransparent().equals(actual.isCertificateTransparent()) && expected.isEnabled().equals(actual.isEnabled()) && expected.isKeyReusable().equals(actual.isKeyReusable()) && expected.getValidityInMonths().equals(actual.getValidityInMonths()) && expected.getLifetimeActions().size() == actual.getLifetimeActions().size() && expected.getKeyUsage().size() == actual.getKeyUsage().size(); } boolean validateCertificate(KeyVaultCertificate expected, KeyVaultCertificate actual) { return expected.getId().equals(actual.getId()) && expected.getKeyId().equals(actual.getKeyId()) && expected.getName().equals(actual.getName()) && expected.getSecretId().equals(actual.getSecretId()) && expected.getProperties().getVersion().equals(actual.getProperties().getVersion()) && expected.getProperties().getCreatedOn().equals(actual.getProperties().getCreatedOn()) && expected.getProperties().getExpiresOn().equals(actual.getProperties().getExpiresOn()) && expected.getProperties().getRecoveryLevel().equals(actual.getProperties().getRecoveryLevel()) && expected.getProperties().getX509Thumbprint().length == actual.getProperties().getX509Thumbprint().length && expected.getCer().length == actual.getCer().length; } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertResponseException(Runnable exceptionThrower, int expectedStatusCode) { assertResponseException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (HttpResponseException e) { assertResponseException(e, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test. * @param expectedStatusCode Expected HTTP status code contained in the error response. */ static void assertResponseException(HttpResponseException exception, int expectedStatusCode) { assertResponseException(exception, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } static void assertResponseException(HttpResponseException exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, exception.getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception e) { assertEquals(exception, e.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients().forEach(httpClient -> Arrays.stream(CertificateServiceVersion.values()) .filter(CertificateClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)))); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link CertificateServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(CertificateServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return CertificateServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList) .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } void validateMapResponse(Map<String, String> expected, Map<String, String> returned) { for (String key : expected.keySet()) { String val = returned.get(key); String expectedVal = expected.get(key); assertEquals(expectedVal, val); } } }
class CertificateClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS); private static final String AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL = "ALL"; private static final String TEST_CERTIFICATE_NAME = "testCert"; @Override protected String getTestName() { return ""; } HttpPipeline getHttpPipeline(HttpClient httpClient) { return getHttpPipeline(httpClient, null); } HttpPipeline getHttpPipeline(HttpClient httpClient, String testTenantId) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("value", "-----BEGIN PRIVATE KEY-----\\n(.+\\n)*-----END PRIVATE KEY-----\\n", "-----BEGIN PRIVATE KEY-----\\nREDACTED\\n-----END PRIVATE KEY-----\\n", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); } @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createCertificateRunner(Consumer<CertificatePolicy> testRunner) { final CertificatePolicy certificatePolicy = CertificatePolicy.getDefault(); testRunner.accept(certificatePolicy); } @Test public abstract void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateDisabledCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateSpecificVersionRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getDeletedCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void recoverDeletedKeyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void backupCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void restoreCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void cancelCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listPropertiesOfCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listPropertiesOfCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateIssuersRunner(Consumer<HashMap<String, CertificateIssuer>> testRunner) { HashMap<String, CertificateIssuer> certificateIssuers = new HashMap<>(); String certificateIssuerName; for (int i = 0; i < 10; i++) { certificateIssuerName = testResourceNamer.randomName("listCertIssuer", 25); certificateIssuers.put(certificateIssuerName, setupIssuer(certificateIssuerName)); } testRunner.accept(certificateIssuers); } void updateIssuerRunner(BiConsumer<CertificateIssuer, CertificateIssuer> testRunner) { String issuerName = testResourceNamer.randomName("testIssuer", 25); final CertificateIssuer certificateIssuer = setupIssuer(issuerName); final CertificateIssuer issuerForUpdate = new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("otherFirst") .setLastName("otherLast") .setEmail("otherFirst.otherLast@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("otherIssuerAccountId") .setEnabled(false) .setOrganizationId("otherOrgId") .setPassword("fakePasswordPlaceholder"); testRunner.accept(certificateIssuer, issuerForUpdate); } @Test public abstract void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateOperationNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); CertificateContact setupContact() { return new CertificateContact() .setName("name") .setEmail("first.last@gmail.com") .setPhone("000-000-0000"); } Boolean validateContact(CertificateContact expected, CertificateContact actual) { return expected.getEmail().equals(actual.getEmail()) && expected.getName().equals(actual.getName()) && expected.getPhone().equals(actual.getPhone()); } @Test public abstract void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateVersionsRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName = testResourceNamer.randomName("listCertVersion", 25); for (int i = 1; i < 5; i++) { certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listDeletedCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 3; i++) { certificateName = testResourceNamer.randomName("listDeletedCert", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void importCertificateRunner(Consumer<ImportCertificateOptions> testRunner) { String certificatePassword = "fakePasswordPlaceholder"; String certificateName = testResourceNamer.randomName("importCertPkcs", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, Base64.getDecoder().decode(FAKE_CERTIFICATE_CONTENT)) .setPassword(certificatePassword) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = testResourceNamer.randomName("importCertPem", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); StringBuilder pemCert = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(pemPath))) { String line; while ((line = br.readLine()) != null) { pemCert.append(line).append("\n"); } } return pemCert.toString().getBytes(); } @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") CertificateIssuer setupIssuer(String issuerName) { return new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("first") .setLastName("last") .setEmail("first.last@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("issuerAccountId") .setEnabled(true) .setOrganizationId("orgId") .setPassword("fakePasswordPlaceholder"); } String toHexString(byte[] x5t) { if (x5t == null) { return ""; } StringBuilder hexString = new StringBuilder(); for (byte b : x5t) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString().replace("-", ""); } X509Certificate loadCerToX509Certificate(KeyVaultCertificateWithPolicy certificate) throws CertificateException, IOException { assertNotNull(certificate.getCer()); ByteArrayInputStream cerStream = new ByteArrayInputStream(certificate.getCer()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); cerStream.close(); return x509Certificate; } boolean issuerCreatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return expected.getAccountId().equals(actual.getAccountId()) && expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } boolean issuerUpdatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return !expected.getAccountId().equals(actual.getAccountId()) && !expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && !expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } CertificatePolicy setupPolicy() { return new CertificatePolicy(WellKnownIssuerNames.SELF, "CN=default") .setKeyUsage(CertificateKeyUsage.KEY_CERT_SIGN, CertificateKeyUsage.KEY_AGREEMENT) .setContentType(CertificateContentType.PKCS12) .setExportable(true) .setKeyType(CertificateKeyType.EC) .setCertificateTransparent(false) .setEnabled(true) .setKeyCurveName(CertificateKeyCurveName.P_384) .setKeyReusable(true) .setValidityInMonths(24) .setLifetimeActions(new LifetimeAction(CertificatePolicyAction.AUTO_RENEW).setDaysBeforeExpiry(40)); } boolean validatePolicy(CertificatePolicy expected, CertificatePolicy actual) { return expected.getKeyType().equals(actual.getKeyType()) && expected.getContentType().equals(actual.getContentType()) && actual.getCreatedOn() != null && expected.getIssuerName().equals(actual.getIssuerName()) && expected.getKeyCurveName().equals(actual.getKeyCurveName()) && expected.isExportable().equals(actual.isExportable()) && expected.isCertificateTransparent().equals(actual.isCertificateTransparent()) && expected.isEnabled().equals(actual.isEnabled()) && expected.isKeyReusable().equals(actual.isKeyReusable()) && expected.getValidityInMonths().equals(actual.getValidityInMonths()) && expected.getLifetimeActions().size() == actual.getLifetimeActions().size() && expected.getKeyUsage().size() == actual.getKeyUsage().size(); } boolean validateCertificate(KeyVaultCertificate expected, KeyVaultCertificate actual) { return expected.getId().equals(actual.getId()) && expected.getKeyId().equals(actual.getKeyId()) && expected.getName().equals(actual.getName()) && expected.getSecretId().equals(actual.getSecretId()) && expected.getProperties().getVersion().equals(actual.getProperties().getVersion()) && expected.getProperties().getCreatedOn().equals(actual.getProperties().getCreatedOn()) && expected.getProperties().getExpiresOn().equals(actual.getProperties().getExpiresOn()) && expected.getProperties().getRecoveryLevel().equals(actual.getProperties().getRecoveryLevel()) && expected.getProperties().getX509Thumbprint().length == actual.getProperties().getX509Thumbprint().length && expected.getCer().length == actual.getCer().length; } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertResponseException(Runnable exceptionThrower, int expectedStatusCode) { assertResponseException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (HttpResponseException e) { assertResponseException(e, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test. * @param expectedStatusCode Expected HTTP status code contained in the error response. */ static void assertResponseException(HttpResponseException exception, int expectedStatusCode) { assertResponseException(exception, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } static void assertResponseException(HttpResponseException exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, exception.getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception e) { assertEquals(exception, e.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients().forEach(httpClient -> Arrays.stream(CertificateServiceVersion.values()) .filter(CertificateClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)))); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link CertificateServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(CertificateServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return CertificateServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList) .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } void validateMapResponse(Map<String, String> expected, Map<String, String> returned) { for (String key : expected.keySet()) { String val = returned.get(key); String expectedVal = expected.get(key); assertEquals(expectedVal, val); } } }
Yes, we do. Let me make sure it's there.
void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); }
KeyVaultCredentialPolicy.clearCache();
void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); }
class CertificateClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS); private static final String AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL = "ALL"; private static final String TEST_CERTIFICATE_NAME = "testCert"; @Override protected String getTestName() { return ""; } HttpPipeline getHttpPipeline(HttpClient httpClient) { return getHttpPipeline(httpClient, null); } HttpPipeline getHttpPipeline(HttpClient httpClient, String testTenantId) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("value", "-----BEGIN PRIVATE KEY-----\\n(.+\\n)*-----END PRIVATE KEY-----\\n", "-----BEGIN PRIVATE KEY-----\\nREDACTED\\n-----END PRIVATE KEY-----\\n", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); } @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createCertificateRunner(Consumer<CertificatePolicy> testRunner) { final CertificatePolicy certificatePolicy = CertificatePolicy.getDefault(); testRunner.accept(certificatePolicy); } @Test public abstract void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateDisabledCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateSpecificVersionRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getDeletedCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void recoverDeletedKeyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void backupCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void restoreCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void cancelCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listPropertiesOfCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listPropertiesOfCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateIssuersRunner(Consumer<HashMap<String, CertificateIssuer>> testRunner) { HashMap<String, CertificateIssuer> certificateIssuers = new HashMap<>(); String certificateIssuerName; for (int i = 0; i < 10; i++) { certificateIssuerName = testResourceNamer.randomName("listCertIssuer", 25); certificateIssuers.put(certificateIssuerName, setupIssuer(certificateIssuerName)); } testRunner.accept(certificateIssuers); } void updateIssuerRunner(BiConsumer<CertificateIssuer, CertificateIssuer> testRunner) { String issuerName = testResourceNamer.randomName("testIssuer", 25); final CertificateIssuer certificateIssuer = setupIssuer(issuerName); final CertificateIssuer issuerForUpdate = new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("otherFirst") .setLastName("otherLast") .setEmail("otherFirst.otherLast@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("otherIssuerAccountId") .setEnabled(false) .setOrganizationId("otherOrgId") .setPassword("fakePasswordPlaceholder"); testRunner.accept(certificateIssuer, issuerForUpdate); } @Test public abstract void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateOperationNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); CertificateContact setupContact() { return new CertificateContact() .setName("name") .setEmail("first.last@gmail.com") .setPhone("000-000-0000"); } Boolean validateContact(CertificateContact expected, CertificateContact actual) { return expected.getEmail().equals(actual.getEmail()) && expected.getName().equals(actual.getName()) && expected.getPhone().equals(actual.getPhone()); } @Test public abstract void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateVersionsRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName = testResourceNamer.randomName("listCertVersion", 25); for (int i = 1; i < 5; i++) { certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listDeletedCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 3; i++) { certificateName = testResourceNamer.randomName("listDeletedCert", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void importCertificateRunner(Consumer<ImportCertificateOptions> testRunner) { String certificatePassword = "fakePasswordPlaceholder"; String certificateName = testResourceNamer.randomName("importCertPkcs", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, Base64.getDecoder().decode(FAKE_CERTIFICATE_CONTENT)) .setPassword(certificatePassword) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = testResourceNamer.randomName("importCertPem", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); StringBuilder pemCert = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(pemPath))) { String line; while ((line = br.readLine()) != null) { pemCert.append(line).append("\n"); } } return pemCert.toString().getBytes(); } @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") CertificateIssuer setupIssuer(String issuerName) { return new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("first") .setLastName("last") .setEmail("first.last@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("issuerAccountId") .setEnabled(true) .setOrganizationId("orgId") .setPassword("fakePasswordPlaceholder"); } String toHexString(byte[] x5t) { if (x5t == null) { return ""; } StringBuilder hexString = new StringBuilder(); for (byte b : x5t) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString().replace("-", ""); } X509Certificate loadCerToX509Certificate(KeyVaultCertificateWithPolicy certificate) throws CertificateException, IOException { assertNotNull(certificate.getCer()); ByteArrayInputStream cerStream = new ByteArrayInputStream(certificate.getCer()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); cerStream.close(); return x509Certificate; } boolean issuerCreatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return expected.getAccountId().equals(actual.getAccountId()) && expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } boolean issuerUpdatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return !expected.getAccountId().equals(actual.getAccountId()) && !expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && !expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } CertificatePolicy setupPolicy() { return new CertificatePolicy(WellKnownIssuerNames.SELF, "CN=default") .setKeyUsage(CertificateKeyUsage.KEY_CERT_SIGN, CertificateKeyUsage.KEY_AGREEMENT) .setContentType(CertificateContentType.PKCS12) .setExportable(true) .setKeyType(CertificateKeyType.EC) .setCertificateTransparent(false) .setEnabled(true) .setKeyCurveName(CertificateKeyCurveName.P_384) .setKeyReusable(true) .setValidityInMonths(24) .setLifetimeActions(new LifetimeAction(CertificatePolicyAction.AUTO_RENEW).setDaysBeforeExpiry(40)); } boolean validatePolicy(CertificatePolicy expected, CertificatePolicy actual) { return expected.getKeyType().equals(actual.getKeyType()) && expected.getContentType().equals(actual.getContentType()) && actual.getCreatedOn() != null && expected.getIssuerName().equals(actual.getIssuerName()) && expected.getKeyCurveName().equals(actual.getKeyCurveName()) && expected.isExportable().equals(actual.isExportable()) && expected.isCertificateTransparent().equals(actual.isCertificateTransparent()) && expected.isEnabled().equals(actual.isEnabled()) && expected.isKeyReusable().equals(actual.isKeyReusable()) && expected.getValidityInMonths().equals(actual.getValidityInMonths()) && expected.getLifetimeActions().size() == actual.getLifetimeActions().size() && expected.getKeyUsage().size() == actual.getKeyUsage().size(); } boolean validateCertificate(KeyVaultCertificate expected, KeyVaultCertificate actual) { return expected.getId().equals(actual.getId()) && expected.getKeyId().equals(actual.getKeyId()) && expected.getName().equals(actual.getName()) && expected.getSecretId().equals(actual.getSecretId()) && expected.getProperties().getVersion().equals(actual.getProperties().getVersion()) && expected.getProperties().getCreatedOn().equals(actual.getProperties().getCreatedOn()) && expected.getProperties().getExpiresOn().equals(actual.getProperties().getExpiresOn()) && expected.getProperties().getRecoveryLevel().equals(actual.getProperties().getRecoveryLevel()) && expected.getProperties().getX509Thumbprint().length == actual.getProperties().getX509Thumbprint().length && expected.getCer().length == actual.getCer().length; } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertResponseException(Runnable exceptionThrower, int expectedStatusCode) { assertResponseException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (HttpResponseException e) { assertResponseException(e, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test. * @param expectedStatusCode Expected HTTP status code contained in the error response. */ static void assertResponseException(HttpResponseException exception, int expectedStatusCode) { assertResponseException(exception, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } static void assertResponseException(HttpResponseException exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, exception.getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception e) { assertEquals(exception, e.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients().forEach(httpClient -> Arrays.stream(CertificateServiceVersion.values()) .filter(CertificateClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)))); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link CertificateServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(CertificateServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return CertificateServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList) .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } void validateMapResponse(Map<String, String> expected, Map<String, String> returned) { for (String key : expected.keySet()) { String val = returned.get(key); String expectedVal = expected.get(key); assertEquals(expectedVal, val); } } }
class CertificateClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS); private static final String AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL = "ALL"; private static final String TEST_CERTIFICATE_NAME = "testCert"; @Override protected String getTestName() { return ""; } HttpPipeline getHttpPipeline(HttpClient httpClient) { return getHttpPipeline(httpClient, null); } HttpPipeline getHttpPipeline(HttpClient httpClient, String testTenantId) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("value", "-----BEGIN PRIVATE KEY-----\\n(.+\\n)*-----END PRIVATE KEY-----\\n", "-----BEGIN PRIVATE KEY-----\\nREDACTED\\n-----END PRIVATE KEY-----\\n", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); } @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createCertificateRunner(Consumer<CertificatePolicy> testRunner) { final CertificatePolicy certificatePolicy = CertificatePolicy.getDefault(); testRunner.accept(certificatePolicy); } @Test public abstract void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateDisabledCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateSpecificVersionRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getDeletedCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void recoverDeletedKeyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void backupCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void restoreCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void cancelCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listPropertiesOfCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listPropertiesOfCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateIssuersRunner(Consumer<HashMap<String, CertificateIssuer>> testRunner) { HashMap<String, CertificateIssuer> certificateIssuers = new HashMap<>(); String certificateIssuerName; for (int i = 0; i < 10; i++) { certificateIssuerName = testResourceNamer.randomName("listCertIssuer", 25); certificateIssuers.put(certificateIssuerName, setupIssuer(certificateIssuerName)); } testRunner.accept(certificateIssuers); } void updateIssuerRunner(BiConsumer<CertificateIssuer, CertificateIssuer> testRunner) { String issuerName = testResourceNamer.randomName("testIssuer", 25); final CertificateIssuer certificateIssuer = setupIssuer(issuerName); final CertificateIssuer issuerForUpdate = new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("otherFirst") .setLastName("otherLast") .setEmail("otherFirst.otherLast@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("otherIssuerAccountId") .setEnabled(false) .setOrganizationId("otherOrgId") .setPassword("fakePasswordPlaceholder"); testRunner.accept(certificateIssuer, issuerForUpdate); } @Test public abstract void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateOperationNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); CertificateContact setupContact() { return new CertificateContact() .setName("name") .setEmail("first.last@gmail.com") .setPhone("000-000-0000"); } Boolean validateContact(CertificateContact expected, CertificateContact actual) { return expected.getEmail().equals(actual.getEmail()) && expected.getName().equals(actual.getName()) && expected.getPhone().equals(actual.getPhone()); } @Test public abstract void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateVersionsRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName = testResourceNamer.randomName("listCertVersion", 25); for (int i = 1; i < 5; i++) { certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listDeletedCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 3; i++) { certificateName = testResourceNamer.randomName("listDeletedCert", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void importCertificateRunner(Consumer<ImportCertificateOptions> testRunner) { String certificatePassword = "fakePasswordPlaceholder"; String certificateName = testResourceNamer.randomName("importCertPkcs", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, Base64.getDecoder().decode(FAKE_CERTIFICATE_CONTENT)) .setPassword(certificatePassword) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = testResourceNamer.randomName("importCertPem", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); StringBuilder pemCert = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(pemPath))) { String line; while ((line = br.readLine()) != null) { pemCert.append(line).append("\n"); } } return pemCert.toString().getBytes(); } @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") CertificateIssuer setupIssuer(String issuerName) { return new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("first") .setLastName("last") .setEmail("first.last@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("issuerAccountId") .setEnabled(true) .setOrganizationId("orgId") .setPassword("fakePasswordPlaceholder"); } String toHexString(byte[] x5t) { if (x5t == null) { return ""; } StringBuilder hexString = new StringBuilder(); for (byte b : x5t) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString().replace("-", ""); } X509Certificate loadCerToX509Certificate(KeyVaultCertificateWithPolicy certificate) throws CertificateException, IOException { assertNotNull(certificate.getCer()); ByteArrayInputStream cerStream = new ByteArrayInputStream(certificate.getCer()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); cerStream.close(); return x509Certificate; } boolean issuerCreatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return expected.getAccountId().equals(actual.getAccountId()) && expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } boolean issuerUpdatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return !expected.getAccountId().equals(actual.getAccountId()) && !expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && !expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } CertificatePolicy setupPolicy() { return new CertificatePolicy(WellKnownIssuerNames.SELF, "CN=default") .setKeyUsage(CertificateKeyUsage.KEY_CERT_SIGN, CertificateKeyUsage.KEY_AGREEMENT) .setContentType(CertificateContentType.PKCS12) .setExportable(true) .setKeyType(CertificateKeyType.EC) .setCertificateTransparent(false) .setEnabled(true) .setKeyCurveName(CertificateKeyCurveName.P_384) .setKeyReusable(true) .setValidityInMonths(24) .setLifetimeActions(new LifetimeAction(CertificatePolicyAction.AUTO_RENEW).setDaysBeforeExpiry(40)); } boolean validatePolicy(CertificatePolicy expected, CertificatePolicy actual) { return expected.getKeyType().equals(actual.getKeyType()) && expected.getContentType().equals(actual.getContentType()) && actual.getCreatedOn() != null && expected.getIssuerName().equals(actual.getIssuerName()) && expected.getKeyCurveName().equals(actual.getKeyCurveName()) && expected.isExportable().equals(actual.isExportable()) && expected.isCertificateTransparent().equals(actual.isCertificateTransparent()) && expected.isEnabled().equals(actual.isEnabled()) && expected.isKeyReusable().equals(actual.isKeyReusable()) && expected.getValidityInMonths().equals(actual.getValidityInMonths()) && expected.getLifetimeActions().size() == actual.getLifetimeActions().size() && expected.getKeyUsage().size() == actual.getKeyUsage().size(); } boolean validateCertificate(KeyVaultCertificate expected, KeyVaultCertificate actual) { return expected.getId().equals(actual.getId()) && expected.getKeyId().equals(actual.getKeyId()) && expected.getName().equals(actual.getName()) && expected.getSecretId().equals(actual.getSecretId()) && expected.getProperties().getVersion().equals(actual.getProperties().getVersion()) && expected.getProperties().getCreatedOn().equals(actual.getProperties().getCreatedOn()) && expected.getProperties().getExpiresOn().equals(actual.getProperties().getExpiresOn()) && expected.getProperties().getRecoveryLevel().equals(actual.getProperties().getRecoveryLevel()) && expected.getProperties().getX509Thumbprint().length == actual.getProperties().getX509Thumbprint().length && expected.getCer().length == actual.getCer().length; } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertResponseException(Runnable exceptionThrower, int expectedStatusCode) { assertResponseException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (HttpResponseException e) { assertResponseException(e, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test. * @param expectedStatusCode Expected HTTP status code contained in the error response. */ static void assertResponseException(HttpResponseException exception, int expectedStatusCode) { assertResponseException(exception, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } static void assertResponseException(HttpResponseException exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, exception.getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception e) { assertEquals(exception, e.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients().forEach(httpClient -> Arrays.stream(CertificateServiceVersion.values()) .filter(CertificateClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)))); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link CertificateServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(CertificateServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return CertificateServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList) .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } void validateMapResponse(Map<String, String> expected, Map<String, String> returned) { for (String key : expected.keySet()) { String val = returned.get(key); String expectedVal = expected.get(key); assertEquals(expectedVal, val); } } }
I think I added this before moving onto `MockTokenCredential`. I can give a shot to removing it.
HttpPipeline getPipeline(HttpClient httpClient, boolean forCleanup) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("token", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode() && !forCleanup) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization")));
HttpPipeline getPipeline(HttpClient httpClient, boolean forCleanup) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("token", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode() && !forCleanup) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class KeyVaultAdministrationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; protected static final boolean IS_MANAGED_HSM_DEPLOYED = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; static final String DISPLAY_NAME = "{displayName}"; @Override protected void beforeTest() { super.beforeTest(); Assumptions.assumeTrue(IS_MANAGED_HSM_DEPLOYED || getTestMode() == TestMode.PLAYBACK); KeyVaultCredentialPolicy.clearCache(); } @Override protected String getTestName() { return ""; } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } /** * Returns a stream of arguments that includes all eligible {@link HttpClient HttpClients}. * * @return A stream of {@link HttpClient HTTP clients} to test. */ static Stream<Arguments> createHttpClients() { return TestBase.getHttpClients().map(Arguments::of); } }
class KeyVaultAdministrationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; protected static final boolean IS_MANAGED_HSM_DEPLOYED = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; static final String DISPLAY_NAME = "{displayName}"; @Override protected void beforeTest() { super.beforeTest(); Assumptions.assumeTrue(IS_MANAGED_HSM_DEPLOYED || getTestMode() == TestMode.PLAYBACK); KeyVaultCredentialPolicy.clearCache(); } @Override protected String getTestName() { return ""; } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } /** * Returns a stream of arguments that includes all eligible {@link HttpClient HttpClients}. * * @return A stream of {@link HttpClient HTTP clients} to test. */ static Stream<Arguments> createHttpClients() { return TestBase.getHttpClients().map(Arguments::of); } }
We set it on `KeyVaultAdministrationClientTestBase`.
void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); }
KeyVaultCredentialPolicy.clearCache();
void beforeTestSetup() { KeyVaultCredentialPolicy.clearCache(); }
class CertificateClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS); private static final String AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL = "ALL"; private static final String TEST_CERTIFICATE_NAME = "testCert"; @Override protected String getTestName() { return ""; } HttpPipeline getHttpPipeline(HttpClient httpClient) { return getHttpPipeline(httpClient, null); } HttpPipeline getHttpPipeline(HttpClient httpClient, String testTenantId) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("value", "-----BEGIN PRIVATE KEY-----\\n(.+\\n)*-----END PRIVATE KEY-----\\n", "-----BEGIN PRIVATE KEY-----\\nREDACTED\\n-----END PRIVATE KEY-----\\n", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); } @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createCertificateRunner(Consumer<CertificatePolicy> testRunner) { final CertificatePolicy certificatePolicy = CertificatePolicy.getDefault(); testRunner.accept(certificatePolicy); } @Test public abstract void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateDisabledCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateSpecificVersionRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getDeletedCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void recoverDeletedKeyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void backupCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void restoreCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void cancelCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listPropertiesOfCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listPropertiesOfCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateIssuersRunner(Consumer<HashMap<String, CertificateIssuer>> testRunner) { HashMap<String, CertificateIssuer> certificateIssuers = new HashMap<>(); String certificateIssuerName; for (int i = 0; i < 10; i++) { certificateIssuerName = testResourceNamer.randomName("listCertIssuer", 25); certificateIssuers.put(certificateIssuerName, setupIssuer(certificateIssuerName)); } testRunner.accept(certificateIssuers); } void updateIssuerRunner(BiConsumer<CertificateIssuer, CertificateIssuer> testRunner) { String issuerName = testResourceNamer.randomName("testIssuer", 25); final CertificateIssuer certificateIssuer = setupIssuer(issuerName); final CertificateIssuer issuerForUpdate = new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("otherFirst") .setLastName("otherLast") .setEmail("otherFirst.otherLast@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("otherIssuerAccountId") .setEnabled(false) .setOrganizationId("otherOrgId") .setPassword("fakePasswordPlaceholder"); testRunner.accept(certificateIssuer, issuerForUpdate); } @Test public abstract void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateOperationNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); CertificateContact setupContact() { return new CertificateContact() .setName("name") .setEmail("first.last@gmail.com") .setPhone("000-000-0000"); } Boolean validateContact(CertificateContact expected, CertificateContact actual) { return expected.getEmail().equals(actual.getEmail()) && expected.getName().equals(actual.getName()) && expected.getPhone().equals(actual.getPhone()); } @Test public abstract void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateVersionsRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName = testResourceNamer.randomName("listCertVersion", 25); for (int i = 1; i < 5; i++) { certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listDeletedCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 3; i++) { certificateName = testResourceNamer.randomName("listDeletedCert", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void importCertificateRunner(Consumer<ImportCertificateOptions> testRunner) { String certificatePassword = "fakePasswordPlaceholder"; String certificateName = testResourceNamer.randomName("importCertPkcs", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, Base64.getDecoder().decode(FAKE_CERTIFICATE_CONTENT)) .setPassword(certificatePassword) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = testResourceNamer.randomName("importCertPem", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); StringBuilder pemCert = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(pemPath))) { String line; while ((line = br.readLine()) != null) { pemCert.append(line).append("\n"); } } return pemCert.toString().getBytes(); } @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") CertificateIssuer setupIssuer(String issuerName) { return new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("first") .setLastName("last") .setEmail("first.last@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("issuerAccountId") .setEnabled(true) .setOrganizationId("orgId") .setPassword("fakePasswordPlaceholder"); } String toHexString(byte[] x5t) { if (x5t == null) { return ""; } StringBuilder hexString = new StringBuilder(); for (byte b : x5t) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString().replace("-", ""); } X509Certificate loadCerToX509Certificate(KeyVaultCertificateWithPolicy certificate) throws CertificateException, IOException { assertNotNull(certificate.getCer()); ByteArrayInputStream cerStream = new ByteArrayInputStream(certificate.getCer()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); cerStream.close(); return x509Certificate; } boolean issuerCreatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return expected.getAccountId().equals(actual.getAccountId()) && expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } boolean issuerUpdatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return !expected.getAccountId().equals(actual.getAccountId()) && !expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && !expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } CertificatePolicy setupPolicy() { return new CertificatePolicy(WellKnownIssuerNames.SELF, "CN=default") .setKeyUsage(CertificateKeyUsage.KEY_CERT_SIGN, CertificateKeyUsage.KEY_AGREEMENT) .setContentType(CertificateContentType.PKCS12) .setExportable(true) .setKeyType(CertificateKeyType.EC) .setCertificateTransparent(false) .setEnabled(true) .setKeyCurveName(CertificateKeyCurveName.P_384) .setKeyReusable(true) .setValidityInMonths(24) .setLifetimeActions(new LifetimeAction(CertificatePolicyAction.AUTO_RENEW).setDaysBeforeExpiry(40)); } boolean validatePolicy(CertificatePolicy expected, CertificatePolicy actual) { return expected.getKeyType().equals(actual.getKeyType()) && expected.getContentType().equals(actual.getContentType()) && actual.getCreatedOn() != null && expected.getIssuerName().equals(actual.getIssuerName()) && expected.getKeyCurveName().equals(actual.getKeyCurveName()) && expected.isExportable().equals(actual.isExportable()) && expected.isCertificateTransparent().equals(actual.isCertificateTransparent()) && expected.isEnabled().equals(actual.isEnabled()) && expected.isKeyReusable().equals(actual.isKeyReusable()) && expected.getValidityInMonths().equals(actual.getValidityInMonths()) && expected.getLifetimeActions().size() == actual.getLifetimeActions().size() && expected.getKeyUsage().size() == actual.getKeyUsage().size(); } boolean validateCertificate(KeyVaultCertificate expected, KeyVaultCertificate actual) { return expected.getId().equals(actual.getId()) && expected.getKeyId().equals(actual.getKeyId()) && expected.getName().equals(actual.getName()) && expected.getSecretId().equals(actual.getSecretId()) && expected.getProperties().getVersion().equals(actual.getProperties().getVersion()) && expected.getProperties().getCreatedOn().equals(actual.getProperties().getCreatedOn()) && expected.getProperties().getExpiresOn().equals(actual.getProperties().getExpiresOn()) && expected.getProperties().getRecoveryLevel().equals(actual.getProperties().getRecoveryLevel()) && expected.getProperties().getX509Thumbprint().length == actual.getProperties().getX509Thumbprint().length && expected.getCer().length == actual.getCer().length; } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertResponseException(Runnable exceptionThrower, int expectedStatusCode) { assertResponseException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (HttpResponseException e) { assertResponseException(e, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test. * @param expectedStatusCode Expected HTTP status code contained in the error response. */ static void assertResponseException(HttpResponseException exception, int expectedStatusCode) { assertResponseException(exception, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } static void assertResponseException(HttpResponseException exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, exception.getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception e) { assertEquals(exception, e.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients().forEach(httpClient -> Arrays.stream(CertificateServiceVersion.values()) .filter(CertificateClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)))); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link CertificateServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(CertificateServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return CertificateServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList) .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } void validateMapResponse(Map<String, String> expected, Map<String, String> returned) { for (String key : expected.keySet()) { String val = returned.get(key); String expectedVal = expected.get(key); assertEquals(expectedVal, val); } } }
class CertificateClientTestBase extends TestProxyTestBase { static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; private static final String AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS = "AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS"; private static final String SERVICE_VERSION_FROM_ENV = Configuration.getGlobalConfiguration().get(AZURE_KEYVAULT_TEST_CERTIFICATE_SERVICE_VERSIONS); private static final String AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL = "ALL"; private static final String TEST_CERTIFICATE_NAME = "testCert"; @Override protected String getTestName() { return ""; } HttpPipeline getHttpPipeline(HttpClient httpClient) { return getHttpPipeline(httpClient, null); } HttpPipeline getHttpPipeline(HttpClient httpClient, String testTenantId) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = testTenantId == null ? Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID") : testTenantId; Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("value", "-----BEGIN PRIVATE KEY-----\\n(.+\\n)*-----END PRIVATE KEY-----\\n", "-----BEGIN PRIVATE KEY-----\\nREDACTED\\n-----END PRIVATE KEY-----\\n", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add( new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode()) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); } @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createCertificateRunner(Consumer<CertificatePolicy> testRunner) { final CertificatePolicy certificatePolicy = CertificatePolicy.getDefault(); testRunner.accept(certificatePolicy); } @Test public abstract void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void createCertificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateDisabledCertificateRunner(BiConsumer<Map<String, String>, Map<String, String>> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("first tag", "first value"); final Map<String, String> updatedTags = new HashMap<>(); tags.put("first tag", "first value"); tags.put("second tag", "second value"); testRunner.accept(tags, updatedTags); } @Test public abstract void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateSpecificVersionRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getDeletedCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void recoverDeletedKeyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void backupCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void restoreCertificateRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void cancelCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateOperationRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion); void updateCertificatePolicyRunner(Consumer<String> testRunner) { testRunner.accept(testResourceNamer.randomName(TEST_CERTIFICATE_NAME, 25)); } @Test public abstract void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listPropertiesOfCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listPropertiesOfCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 2; i++) { certificateName = testResourceNamer.randomName("listCertKey", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); void createIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void getCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); void deleteCertificateIssuerRunner(Consumer<CertificateIssuer> testRunner) { final CertificateIssuer certificateIssuer = setupIssuer(testResourceNamer.randomName("testIssuer", 25)); testRunner.accept(certificateIssuer); } @Test public abstract void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateIssuersRunner(Consumer<HashMap<String, CertificateIssuer>> testRunner) { HashMap<String, CertificateIssuer> certificateIssuers = new HashMap<>(); String certificateIssuerName; for (int i = 0; i < 10; i++) { certificateIssuerName = testResourceNamer.randomName("listCertIssuer", 25); certificateIssuers.put(certificateIssuerName, setupIssuer(certificateIssuerName)); } testRunner.accept(certificateIssuers); } void updateIssuerRunner(BiConsumer<CertificateIssuer, CertificateIssuer> testRunner) { String issuerName = testResourceNamer.randomName("testIssuer", 25); final CertificateIssuer certificateIssuer = setupIssuer(issuerName); final CertificateIssuer issuerForUpdate = new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("otherFirst") .setLastName("otherLast") .setEmail("otherFirst.otherLast@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("otherIssuerAccountId") .setEnabled(false) .setOrganizationId("otherOrgId") .setPassword("fakePasswordPlaceholder"); testRunner.accept(certificateIssuer, issuerForUpdate); } @Test public abstract void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificateOperationNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); @Test public abstract void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); CertificateContact setupContact() { return new CertificateContact() .setName("name") .setEmail("first.last@gmail.com") .setPhone("000-000-0000"); } Boolean validateContact(CertificateContact expected, CertificateContact actual) { return expected.getEmail().equals(actual.getEmail()) && expected.getName().equals(actual.getName()) && expected.getPhone().equals(actual.getPhone()); } @Test public abstract void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listCertificateVersionsRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName = testResourceNamer.randomName("listCertVersion", 25); for (int i = 1; i < 5; i++) { certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion); void listDeletedCertificatesRunner(Consumer<List<String>> testRunner) { List<String> certificates = new ArrayList<>(); String certificateName; for (int i = 0; i < 3; i++) { certificateName = testResourceNamer.randomName("listDeletedCert", 25); certificates.add(certificateName); } testRunner.accept(certificates); } @Test public abstract void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); void importCertificateRunner(Consumer<ImportCertificateOptions> testRunner) { String certificatePassword = "fakePasswordPlaceholder"; String certificateName = testResourceNamer.randomName("importCertPkcs", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, Base64.getDecoder().decode(FAKE_CERTIFICATE_CONTENT)) .setPassword(certificatePassword) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException; void importPemCertificateRunner(Consumer<ImportCertificateOptions> testRunner) throws IOException { byte[] certificateContent = readCertificate("pemCert.pem"); String certificateName = testResourceNamer.randomName("importCertPem", 25); HashMap<String, String> tags = new HashMap<>(); tags.put("key", "val"); ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions(certificateName, certificateContent) .setPolicy(new CertificatePolicy("Self", "CN=AzureSDK") .setContentType(CertificateContentType.PEM)) .setEnabled(true) .setTags(tags); testRunner.accept(importCertificateOptions); } @Test public abstract void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion); private byte[] readCertificate(String certName) throws IOException { String pemPath = getClass().getClassLoader().getResource(certName).getPath(); StringBuilder pemCert = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(pemPath))) { String line; while ((line = br.readLine()) != null) { pemCert.append(line).append("\n"); } } return pemCert.toString().getBytes(); } @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") CertificateIssuer setupIssuer(String issuerName) { return new CertificateIssuer(issuerName, "Test") .setAdministratorContacts(Arrays.asList(new AdministratorContact() .setFirstName("first") .setLastName("last") .setEmail("first.last@hotmail.com") .setPhone("000-000-0000"))) .setAccountId("issuerAccountId") .setEnabled(true) .setOrganizationId("orgId") .setPassword("fakePasswordPlaceholder"); } String toHexString(byte[] x5t) { if (x5t == null) { return ""; } StringBuilder hexString = new StringBuilder(); for (byte b : x5t) { String hex = Integer.toHexString(0xFF & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString().replace("-", ""); } X509Certificate loadCerToX509Certificate(KeyVaultCertificateWithPolicy certificate) throws CertificateException, IOException { assertNotNull(certificate.getCer()); ByteArrayInputStream cerStream = new ByteArrayInputStream(certificate.getCer()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream); cerStream.close(); return x509Certificate; } boolean issuerCreatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return expected.getAccountId().equals(actual.getAccountId()) && expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } boolean issuerUpdatedCorrectly(CertificateIssuer expected, CertificateIssuer actual) { return !expected.getAccountId().equals(actual.getAccountId()) && !expected.isEnabled().equals(actual.isEnabled()) && (actual.getCreatedOn() != null) && (actual.getUpdatedOn() != null) && (actual.getId() != null) && (actual.getId().length() > 0) && expected.getName().equals(actual.getName()) && !expected.getOrganizationId().equals(actual.getOrganizationId()) && expected.getAdministratorContacts().size() == actual.getAdministratorContacts().size(); } CertificatePolicy setupPolicy() { return new CertificatePolicy(WellKnownIssuerNames.SELF, "CN=default") .setKeyUsage(CertificateKeyUsage.KEY_CERT_SIGN, CertificateKeyUsage.KEY_AGREEMENT) .setContentType(CertificateContentType.PKCS12) .setExportable(true) .setKeyType(CertificateKeyType.EC) .setCertificateTransparent(false) .setEnabled(true) .setKeyCurveName(CertificateKeyCurveName.P_384) .setKeyReusable(true) .setValidityInMonths(24) .setLifetimeActions(new LifetimeAction(CertificatePolicyAction.AUTO_RENEW).setDaysBeforeExpiry(40)); } boolean validatePolicy(CertificatePolicy expected, CertificatePolicy actual) { return expected.getKeyType().equals(actual.getKeyType()) && expected.getContentType().equals(actual.getContentType()) && actual.getCreatedOn() != null && expected.getIssuerName().equals(actual.getIssuerName()) && expected.getKeyCurveName().equals(actual.getKeyCurveName()) && expected.isExportable().equals(actual.isExportable()) && expected.isCertificateTransparent().equals(actual.isCertificateTransparent()) && expected.isEnabled().equals(actual.isEnabled()) && expected.isKeyReusable().equals(actual.isKeyReusable()) && expected.getValidityInMonths().equals(actual.getValidityInMonths()) && expected.getLifetimeActions().size() == actual.getLifetimeActions().size() && expected.getKeyUsage().size() == actual.getKeyUsage().size(); } boolean validateCertificate(KeyVaultCertificate expected, KeyVaultCertificate actual) { return expected.getId().equals(actual.getId()) && expected.getKeyId().equals(actual.getKeyId()) && expected.getName().equals(actual.getName()) && expected.getSecretId().equals(actual.getSecretId()) && expected.getProperties().getVersion().equals(actual.getProperties().getVersion()) && expected.getProperties().getCreatedOn().equals(actual.getProperties().getCreatedOn()) && expected.getProperties().getExpiresOn().equals(actual.getProperties().getExpiresOn()) && expected.getProperties().getRecoveryLevel().equals(actual.getProperties().getRecoveryLevel()) && expected.getProperties().getX509Thumbprint().length == actual.getProperties().getX509Thumbprint().length && expected.getCer().length == actual.getCer().length; } public String getEndpoint() { final String endpoint = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_ENDPOINT", "https: Objects.requireNonNull(endpoint); return endpoint; } static void assertResponseException(Runnable exceptionThrower, int expectedStatusCode) { assertResponseException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (HttpResponseException e) { assertResponseException(e, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpRequestException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test. * @param expectedStatusCode Expected HTTP status code contained in the error response. */ static void assertResponseException(HttpResponseException exception, int expectedStatusCode) { assertResponseException(exception, HttpResponseException.class, expectedStatusCode); } static void assertResponseException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } static void assertResponseException(HttpResponseException exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, exception.getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception e) { assertEquals(exception, e.getClass()); } } public void sleepInRecordMode(long millis) { if (interceptorManager.isPlaybackMode()) { return; } try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and * service versions that should be tested. * * @return A stream of HttpClient and service version combinations to test. */ static Stream<Arguments> getTestParameters() { List<Arguments> argumentsList = new ArrayList<>(); getHttpClients().forEach(httpClient -> Arrays.stream(CertificateServiceVersion.values()) .filter(CertificateClientTestBase::shouldServiceVersionBeTested) .forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)))); return argumentsList.stream(); } /** * Returns whether the given service version match the rules of test framework. * * <ul> * <li>Using latest service version as default if no environment variable is set.</li> * <li>If it's set to ALL, all Service versions in {@link CertificateServiceVersion} will be tested.</li> * <li>Otherwise, Service version string should match env variable.</li> * </ul> * * Environment values currently supported are: "ALL", "${version}". * Use comma to separate http clients want to test. * e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0} * * @param serviceVersion ServiceVersion needs to check. * * @return Boolean indicates whether filters out the service version or not. */ private static boolean shouldServiceVersionBeTested(CertificateServiceVersion serviceVersion) { if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) { return CertificateServiceVersion.getLatest().equals(serviceVersion); } if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) { return true; } String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(","); return Arrays.stream(configuredServiceVersionList) .anyMatch(configuredServiceVersion -> serviceVersion.getVersion().equals(configuredServiceVersion.trim())); } void validateMapResponse(Map<String, String> expected, Map<String, String> returned) { for (String key : expected.keySet()) { String val = returned.get(key); String expectedVal = expected.get(key); assertEquals(expectedVal, val); } } }
Looks like we needed it :v
HttpPipeline getPipeline(HttpClient httpClient, boolean forCleanup) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("token", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode() && !forCleanup) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization")));
HttpPipeline getPipeline(HttpClient httpClient, boolean forCleanup) { TokenCredential credential; if (!interceptorManager.isPlaybackMode()) { String clientId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_ID"); String clientKey = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_CLIENT_SECRET"); String tenantId = Configuration.getGlobalConfiguration().get("AZURE_KEYVAULT_TENANT_ID"); Objects.requireNonNull(clientId, "The client id cannot be null"); Objects.requireNonNull(clientKey, "The client key cannot be null"); Objects.requireNonNull(tenantId, "The tenant id cannot be null"); credential = new ClientSecretCredentialBuilder() .clientSecret(clientKey) .clientId(clientId) .tenantId(tenantId) .additionallyAllowedTenants("*") .build(); if (interceptorManager.isRecordMode()) { List<TestProxySanitizer> customSanitizers = new ArrayList<>(); customSanitizers.add(new TestProxySanitizer("token", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); interceptorManager.addSanitizers(customSanitizers); } } else { credential = new MockTokenCredential(); List<TestProxyRequestMatcher> customMatchers = new ArrayList<>(); customMatchers.add(new BodilessMatcher()); customMatchers.add(new CustomMatcher().setExcludedHeaders(Collections.singletonList("Authorization"))); interceptorManager.addMatchers(customMatchers); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(null, SDK_NAME, SDK_VERSION, Configuration.getGlobalConfiguration().clone())); HttpPolicyProviders.addBeforeRetryPolicies(policies); RetryStrategy strategy = new ExponentialBackoff(5, Duration.ofSeconds(2), Duration.ofSeconds(16)); policies.add(new RetryPolicy(strategy)); if (credential != null) { policies.add(new KeyVaultCredentialPolicy(credential, interceptorManager.isPlaybackMode())); } HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); if (interceptorManager.isRecordMode() && !forCleanup) { policies.add(interceptorManager.getRecordPolicy()); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient) .build(); }
class KeyVaultAdministrationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; protected static final boolean IS_MANAGED_HSM_DEPLOYED = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; static final String DISPLAY_NAME = "{displayName}"; @Override protected void beforeTest() { super.beforeTest(); Assumptions.assumeTrue(IS_MANAGED_HSM_DEPLOYED || getTestMode() == TestMode.PLAYBACK); KeyVaultCredentialPolicy.clearCache(); } @Override protected String getTestName() { return ""; } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } /** * Returns a stream of arguments that includes all eligible {@link HttpClient HttpClients}. * * @return A stream of {@link HttpClient HTTP clients} to test. */ static Stream<Arguments> createHttpClients() { return TestBase.getHttpClients().map(Arguments::of); } }
class KeyVaultAdministrationClientTestBase extends TestProxyTestBase { private static final String SDK_NAME = "client_name"; private static final String SDK_VERSION = "client_version"; protected static final boolean IS_MANAGED_HSM_DEPLOYED = Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT") != null; static final String DISPLAY_NAME = "{displayName}"; @Override protected void beforeTest() { super.beforeTest(); Assumptions.assumeTrue(IS_MANAGED_HSM_DEPLOYED || getTestMode() == TestMode.PLAYBACK); KeyVaultCredentialPolicy.clearCache(); } @Override protected String getTestName() { return ""; } public String getEndpoint() { final String endpoint = interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get("AZURE_MANAGEDHSM_ENDPOINT"); Objects.requireNonNull(endpoint); return endpoint; } /** * Returns a stream of arguments that includes all eligible {@link HttpClient HttpClients}. * * @return A stream of {@link HttpClient HTTP clients} to test. */ static Stream<Arguments> createHttpClients() { return TestBase.getHttpClients().map(Arguments::of); } }
I don't see where you are testing the that caller can at least view the second error code/message - but maybe I am missing it?
public void uploadFails() { Flux<ByteBuffer> flux = Flux.create(sink -> { sha256.update(CHUNK); sink.next(ByteBuffer.wrap(CHUNK)); sha256.update(CHUNK); sink.next(ByteBuffer.wrap(CHUNK)); sink.complete(); }); BiFunction<HttpRequest, Integer, HttpResponse> onChunk = (r, c) -> { if (c == 3) { HttpHeaders responseHeaders = new HttpHeaders().add("Content-Type", String.valueOf("application/json")); String error = "{\"errors\":[{\"code\":\"BLOB_UPLOAD_INVALID\",\"message\":\"blob upload invalid\"}, {\"code\":\"BLOB_UPLOAD_FOO\",\"message\":\"blob upload foo\"}]}"; return new MockHttpResponse(r, 404, responseHeaders, error.getBytes(StandardCharsets.UTF_8)); } return null; }; Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); BinaryData content = BinaryData.fromFlux(flux, (long) CHUNK_SIZE * 2, false).block(); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest, onChunk)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest, onChunk)); ResourceNotFoundException ex = assertThrows(ResourceNotFoundException.class, () -> SyncAsyncExtension.execute( () -> client.uploadBlob(content), () -> asyncClient.uploadBlob(content))); assertAcrException(ex, "BLOB_UPLOAD_INVALID"); }
String error = "{\"errors\":[{\"code\":\"BLOB_UPLOAD_INVALID\",\"message\":\"blob upload invalid\"}, {\"code\":\"BLOB_UPLOAD_FOO\",\"message\":\"blob upload foo\"}]}";
public void uploadFails() { Flux<ByteBuffer> flux = Flux.create(sink -> { sha256.update(CHUNK); sink.next(ByteBuffer.wrap(CHUNK)); sha256.update(CHUNK); sink.next(ByteBuffer.wrap(CHUNK)); sink.complete(); }); BiFunction<HttpRequest, Integer, HttpResponse> onChunk = (r, c) -> { if (c == 3) { HttpHeaders responseHeaders = new HttpHeaders().add("Content-Type", String.valueOf("application/json")); String error = "{\"errors\":[{\"code\":\"BLOB_UPLOAD_INVALID\",\"message\":\"blob upload invalid\"}, {\"code\":\"BLOB_UPLOAD_FOO\",\"message\":\"blob upload foo\"}]}"; return new MockHttpResponse(r, 404, responseHeaders, error.getBytes(StandardCharsets.UTF_8)); } return null; }; Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); BinaryData content = BinaryData.fromFlux(flux, (long) CHUNK_SIZE * 2, false).block(); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest, onChunk)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest, onChunk)); ResourceNotFoundException ex = assertThrows(ResourceNotFoundException.class, () -> SyncAsyncExtension.execute( () -> client.uploadBlob(content), () -> asyncClient.uploadBlob(content))); assertAcrException(ex, "BLOB_UPLOAD_INVALID"); }
class ContainerRegistryContentClientTests { private static final BinaryData SMALL_CONTENT = BinaryData.fromString("foobar"); private static final String SMALL_CONTENT_SHA256 = "sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"; private static final String DEFAULT_MANIFEST_CONTENT_TYPE = "*/*," + ManifestMediaType.OCI_MANIFEST + "," + ManifestMediaType.DOCKER_MANIFEST + ",application/vnd.oci.image.index.v1+json" + ",application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.cncf.oras.artifact.manifest.v1+json"; private static final BinaryData MANIFEST_DATA = BinaryData.fromObject(MANIFEST); private static final BinaryData OCI_INDEX = BinaryData.fromString("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\"," + "\"manifests\":[{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"size\":7143,\"digest\":\"sha256:e692418e4cbaf90ca69d05a66403747baa33ee08806650b51fab815ad7fc331f\"," + "\"platform\":{\"architecture\":\"ppc64le\",\"os\":\"linux\"}}]}"); private static final String OCI_INDEX_DIGEST = "sha256:226bb568af1e417421f2f8053cd2847bdb5fcc52c7ed93823abdb595881c2b02"; private static final Random RANDOM = new Random(42); private static final byte[] CHUNK = new byte[CHUNK_SIZE]; static { RANDOM.nextBytes(CHUNK); } private MessageDigest sha256; @BeforeEach void beforeEach() { try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { fail(e); } } @Test public void downloadBlobWrongDigestInHeaderSync() { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); assertThrows(ServiceResponseException.class, () -> client.downloadStream("some-digest", Channels.newChannel(stream))); } @Test public void downloadManigestWrongDigestInHeaderSync() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); assertThrows(ServiceResponseException.class, () -> client.getManifest("latest")); } @Test public void downloadBlobWrongDigestInHeaderAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StepVerifier.create(asyncClient.downloadStream("some-digest") .flatMap(response -> FluxUtil.writeToOutputStream(response.toFluxByteBuffer(), stream))) .expectError(ServiceResponseException.class) .verify(); } @Test public void getManifestWrongDigestInHeaderAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); StepVerifier.create(asyncClient.getManifest("latest")) .expectError(ServiceResponseException.class) .verify(); } @Test public void downloadBlobWrongResponseSync() { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); assertThrows(ServiceResponseException.class, () -> client.downloadStream(SMALL_CONTENT_SHA256, Channels.newChannel(stream))); } @Test public void getManifestWrongResponseSync() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); assertThrows(ServiceResponseException.class, () -> client.getManifest("latest")); } @Test public void downloadBlobWrongResponseAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StepVerifier.create(asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(response -> FluxUtil.writeToOutputStream(response.toFluxByteBuffer(), stream))) .expectError(ServiceResponseException.class) .verify(); } @Test public void getManifestWrongResponseAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); StepVerifier.create(asyncClient.getManifest("latest")) .expectError(ServiceResponseException.class) .verify(); } @SyncAsyncTest public void getManifest() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, null)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, null)); GetManifestResult result = SyncAsyncExtension.execute( () -> client.getManifest(MANIFEST_DIGEST), () -> asyncClient.getManifest(MANIFEST_DIGEST)); assertArrayEquals(MANIFEST_DATA.toBytes(), result.getManifest().toBytes()); assertNotNull(result.getManifest().toObject(ManifestMediaType.class)); assertEquals(ManifestMediaType.OCI_MANIFEST, result.getManifestMediaType()); } @SyncAsyncTest public void getManifestWithDockerType() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, ManifestMediaType.DOCKER_MANIFEST)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, ManifestMediaType.DOCKER_MANIFEST)); Response<GetManifestResult> result = SyncAsyncExtension.execute( () -> client.getManifestWithResponse(MANIFEST_DIGEST, Context.NONE), () -> asyncClient.getManifestWithResponse(MANIFEST_DIGEST)); assertArrayEquals(MANIFEST_DATA.toBytes(), result.getValue().getManifest().toBytes()); assertNotNull(result.getValue().getManifest().toObject(OciImageManifest.class)); assertEquals(ManifestMediaType.DOCKER_MANIFEST, result.getValue().getManifestMediaType()); } @SyncAsyncTest public void getManifestWithOciIndexType() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(OCI_INDEX, OCI_INDEX_DIGEST, OCI_INDEX_MEDIA_TYPE)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(OCI_INDEX, OCI_INDEX_DIGEST, OCI_INDEX_MEDIA_TYPE)); Response<GetManifestResult> result = SyncAsyncExtension.execute( () -> client.getManifestWithResponse(OCI_INDEX_DIGEST, Context.NONE), () -> asyncClient.getManifestWithResponse(OCI_INDEX_DIGEST)); assertArrayEquals(OCI_INDEX.toBytes(), result.getValue().getManifest().toBytes()); assertEquals(OCI_INDEX_MEDIA_TYPE, result.getValue().getManifestMediaType()); } @SyncAsyncTest public void downloadBlobOneChunk() throws IOException { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); SyncAsyncExtension.execute( () -> client.downloadStream(SMALL_CONTENT_SHA256, Channels.newChannel(stream)), () -> asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), stream))); stream.flush(); assertArrayEquals(SMALL_CONTENT.toBytes(), stream.toByteArray()); } @SyncAsyncTest public void downloadBlobMultipleChunks() throws IOException { BinaryData content = getDataSync((int) (CHUNK_SIZE * 2.3), sha256); String expectedDigest = "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(content, expectedDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(content, expectedDigest)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); WritableByteChannel channel = Channels.newChannel(stream); SyncAsyncExtension.execute( () -> client.downloadStream(expectedDigest, Channels.newChannel(stream)), () -> asyncClient.downloadStream(expectedDigest) .flatMap(result -> FluxUtil.writeToWritableByteChannel(result.toFluxByteBuffer(), channel))); stream.flush(); assertArrayEquals(content.toBytes(), stream.toByteArray()); } @SyncAsyncTest public void uploadBlobSmall() { BinaryData content = getDataSync((int) (CHUNK_SIZE * 0.1), sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(content), () -> asyncClient.uploadBlob(content)); } @SyncAsyncTest public void uploadBlobSmallChunks() { Flux<ByteBuffer> content = getDataAsync(CHUNK_SIZE * 2, CHUNK_SIZE / 10, sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromFlux(content).block()), () -> asyncClient.uploadBlob(content)); } @SyncAsyncTest public void uploadBlobBigChunks() { Flux<ByteBuffer> content = getDataAsync(CHUNK_SIZE * 2, (int) (CHUNK_SIZE * 1.5), sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromFlux(content).block()), () -> asyncClient.uploadBlob(content)); } private ByteBuffer slice(ByteBuffer buffer, int offset, int length) { Buffer limited = buffer.duplicate().position(offset).limit(offset + length); return (ByteBuffer) limited; } @Test public void uploadVariableChunkSize() { ByteBuffer buf = ByteBuffer.wrap(CHUNK); Flux<ByteBuffer> content = Flux.create(sink -> { sink.next(slice(buf, 0, 1)); sink.next(slice(buf, 1, 100)); sink.next(slice(buf, 101, 1000)); sink.complete(); }); ByteBuffer full = slice(buf, 0, 1101); sha256.update(full.asReadOnlyBuffer()); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); StepVerifier.create(asyncClient.uploadBlob(content)) .expectNextCount(1) .verifyComplete(); } @Test public void uploadFailWhileReadingInput() { Flux<ByteBuffer> content = Flux.create(sink -> { byte[] data = new byte[100]; new Random().nextBytes(data); sink.next(ByteBuffer.wrap(data)); sink.error(new IllegalStateException("foo")); }); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(() -> "foo")); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(() -> "foo")); assertThrows(IllegalStateException.class, () -> client.uploadBlob(BinaryData.fromFlux(content).block())); StepVerifier.create(asyncClient.uploadBlob(content)) .expectError(IllegalStateException.class) .verify(); } @Test public void uploadFromFile() throws IOException { File input = File.createTempFile("temp", "in"); Files.write(input.toPath(), CHUNK, StandardOpenOption.APPEND); sha256.update(CHUNK); byte[] secondChunk = Arrays.copyOfRange(CHUNK, 0, 100); Files.write(input.toPath(), secondChunk, StandardOpenOption.APPEND); sha256.update(secondChunk); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); StepVerifier.create(asyncClient.uploadBlob(BinaryData.fromFile(input.toPath()))) .expectNextCount(1) .verifyComplete(); } @SyncAsyncTest public void uploadFromStream() throws IOException { ByteBuffer data = slice(ByteBuffer.wrap(CHUNK), 0, 1024 * 100); sha256.update(data.asReadOnlyBuffer()); try (ByteBufferBackedInputStream stream = new ByteBufferBackedInputStream(data)) { Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromStream(stream)), () -> asyncClient.uploadBlob(BinaryData.fromStream(stream))); } } @SyncAsyncTest private void assertAcrException(HttpResponseException ex, String code) { assertInstanceOf(ResponseError.class, ex.getValue()); ResponseError error = (ResponseError) ex.getValue(); assertEquals(code, error.getCode()); } @Test public void downloadToFile() throws IOException { File output = File.createTempFile("temp", "in"); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); try (FileOutputStream outputStream = new FileOutputStream(output)) { StepVerifier.create(asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), outputStream))) .verifyComplete(); outputStream.flush(); assertArrayEquals(SMALL_CONTENT.toBytes(), Files.readAllBytes(output.toPath())); } } public static HttpClient createDownloadContentClient(BinaryData content, String digest) { try (InputStream contentStream = content.toStream()) { AtomicLong expectedStartPosition = new AtomicLong(0); long contentLength = content.getLength(); return new MockHttpClient(request -> { long start = expectedStartPosition.get(); long end = Math.min(start + CHUNK_SIZE, contentLength); if (start >= contentLength) { fail("Got download chunk on completed blob"); } HttpRange expectedRange = new HttpRange(start, (long) CHUNK_SIZE); assertEquals(expectedRange.toString(), request.getHeaders().getValue(HttpHeaderName.RANGE)); byte[] response = new byte[(int) (end - start)]; try { contentStream.read(response); } catch (IOException e) { fail(e); } HttpHeaders headers = new HttpHeaders() .add("Content-Range", String.format("bytes %s-%s/%s", start, end, contentLength)) .add(UtilsImpl.DOCKER_DIGEST_HEADER_NAME, digest); expectedStartPosition.set(start + CHUNK_SIZE); return new MockHttpResponse(request, 206, headers, response); }); } catch (IOException e) { fail(e); throw new RuntimeException(e); } } public static HttpClient createClientManifests(BinaryData content, String digest, ManifestMediaType returnContentType) { return new MockHttpClient(request -> { assertEquals(DEFAULT_MANIFEST_CONTENT_TYPE, request.getHeaders().getValue(HttpHeaderName.ACCEPT)); HttpHeaders headers = new HttpHeaders() .add(UtilsImpl.DOCKER_DIGEST_HEADER_NAME, digest) .add(HttpHeaderName.CONTENT_TYPE, returnContentType == null ? ManifestMediaType.OCI_MANIFEST.toString() : returnContentType.toString()); return new MockHttpResponse(request, 200, headers, content.toBytes()); }); } public static HttpClient createUploadContentClient(Supplier<String> calculateDigest, BiFunction<HttpRequest, Integer, HttpResponse> onChunk) { AtomicInteger callNumber = new AtomicInteger(); return new MockHttpClient(request -> { String expectedReceivedLocation = String.valueOf(callNumber.getAndIncrement()); HttpHeaders responseHeaders = new HttpHeaders().add("Location", String.valueOf(callNumber.get())); if (request.getHttpMethod() == HttpMethod.POST) { assertEquals(0, callNumber.get() - 1); return new MockHttpResponse(request, 202, responseHeaders); } else if (request.getHttpMethod() == HttpMethod.PATCH) { assertEquals("/" + expectedReceivedLocation, request.getUrl().getPath()); HttpResponse response = onChunk.apply(request, callNumber.get()); if (response == null) { response = new MockHttpResponse(request, 202, responseHeaders); } return response; } else if (request.getHttpMethod() == HttpMethod.PUT) { String expectedDigest = calculateDigest.get(); try { assertEquals(request.getUrl().getQuery(), "digest=" + URLEncoder.encode(expectedDigest, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { fail(e); } assertEquals("/" + expectedReceivedLocation, request.getUrl().getPath()); responseHeaders.add(DOCKER_DIGEST_HEADER_NAME, expectedDigest); return new MockHttpResponse(request, 201, responseHeaders); } return new MockHttpResponse(request, 404); }); } public static HttpClient createUploadContentClient(Supplier<String> calculateDigest) { return createUploadContentClient(calculateDigest, (r, c) -> null); } private BinaryData getDataSync(int size, MessageDigest sha256) { return BinaryData.fromFlux(getDataAsync(size, CHUNK_SIZE, sha256)).block(); } private Flux<ByteBuffer> getDataAsync(long size, int chunkSize, MessageDigest sha256) { return Flux.create(sink -> { long sent = 0; while (sent < size) { ByteBuffer buffer = ByteBuffer.wrap(CHUNK); if (sent + chunkSize > size) { buffer.limit((int) (size - sent)); } sha256.update(buffer.asReadOnlyBuffer()); sink.next(buffer); sent += chunkSize; } sink.complete(); }); } private ContainerRegistryContentClient createSyncClient(HttpClient httpClient) { return new ContainerRegistryContentClientBuilder() .endpoint("https: .repositoryName("foo") .httpClient(httpClient) .buildClient(); } private ContainerRegistryContentAsyncClient createAsyncClient(HttpClient httpClient) { return new ContainerRegistryContentClientBuilder() .endpoint("https: .repositoryName("foo") .httpClient(httpClient) .buildAsyncClient(); } static class MockHttpClient implements HttpClient { private final Function<HttpRequest, HttpResponse> requestToResponse; MockHttpClient(Function<HttpRequest, HttpResponse> requestToResponse) { this.requestToResponse = requestToResponse; } @Override public Mono<HttpResponse> send(HttpRequest httpRequest) { return Mono.just(requestToResponse.apply(httpRequest)); } @Override public HttpResponse sendSync(HttpRequest httpRequest, Context context) { return requestToResponse.apply(httpRequest); } } }
class ContainerRegistryContentClientTests { private static final BinaryData SMALL_CONTENT = BinaryData.fromString("foobar"); private static final String SMALL_CONTENT_SHA256 = "sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"; private static final String DEFAULT_MANIFEST_CONTENT_TYPE = "*/*," + ManifestMediaType.OCI_MANIFEST + "," + ManifestMediaType.DOCKER_MANIFEST + ",application/vnd.oci.image.index.v1+json" + ",application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.cncf.oras.artifact.manifest.v1+json"; private static final BinaryData MANIFEST_DATA = BinaryData.fromObject(MANIFEST); private static final BinaryData OCI_INDEX = BinaryData.fromString("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\"," + "\"manifests\":[{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"size\":7143,\"digest\":\"sha256:e692418e4cbaf90ca69d05a66403747baa33ee08806650b51fab815ad7fc331f\"," + "\"platform\":{\"architecture\":\"ppc64le\",\"os\":\"linux\"}}]}"); private static final String OCI_INDEX_DIGEST = "sha256:226bb568af1e417421f2f8053cd2847bdb5fcc52c7ed93823abdb595881c2b02"; private static final Random RANDOM = new Random(42); private static final byte[] CHUNK = new byte[CHUNK_SIZE]; static { RANDOM.nextBytes(CHUNK); } private MessageDigest sha256; @BeforeEach void beforeEach() { try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { fail(e); } } @Test public void downloadBlobWrongDigestInHeaderSync() { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); assertThrows(ServiceResponseException.class, () -> client.downloadStream("some-digest", Channels.newChannel(stream))); } @Test public void downloadManigestWrongDigestInHeaderSync() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); assertThrows(ServiceResponseException.class, () -> client.getManifest("latest")); } @Test public void downloadBlobWrongDigestInHeaderAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StepVerifier.create(asyncClient.downloadStream("some-digest") .flatMap(response -> FluxUtil.writeToOutputStream(response.toFluxByteBuffer(), stream))) .expectError(ServiceResponseException.class) .verify(); } @Test public void getManifestWrongDigestInHeaderAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); StepVerifier.create(asyncClient.getManifest("latest")) .expectError(ServiceResponseException.class) .verify(); } @Test public void downloadBlobWrongResponseSync() { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); assertThrows(ServiceResponseException.class, () -> client.downloadStream(SMALL_CONTENT_SHA256, Channels.newChannel(stream))); } @Test public void getManifestWrongResponseSync() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); assertThrows(ServiceResponseException.class, () -> client.getManifest("latest")); } @Test public void downloadBlobWrongResponseAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StepVerifier.create(asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(response -> FluxUtil.writeToOutputStream(response.toFluxByteBuffer(), stream))) .expectError(ServiceResponseException.class) .verify(); } @Test public void getManifestWrongResponseAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); StepVerifier.create(asyncClient.getManifest("latest")) .expectError(ServiceResponseException.class) .verify(); } @SyncAsyncTest public void getManifest() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, null)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, null)); GetManifestResult result = SyncAsyncExtension.execute( () -> client.getManifest(MANIFEST_DIGEST), () -> asyncClient.getManifest(MANIFEST_DIGEST)); assertArrayEquals(MANIFEST_DATA.toBytes(), result.getManifest().toBytes()); assertNotNull(result.getManifest().toObject(ManifestMediaType.class)); assertEquals(ManifestMediaType.OCI_MANIFEST, result.getManifestMediaType()); } @SyncAsyncTest public void getManifestWithDockerType() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, ManifestMediaType.DOCKER_MANIFEST)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, ManifestMediaType.DOCKER_MANIFEST)); Response<GetManifestResult> result = SyncAsyncExtension.execute( () -> client.getManifestWithResponse(MANIFEST_DIGEST, Context.NONE), () -> asyncClient.getManifestWithResponse(MANIFEST_DIGEST)); assertArrayEquals(MANIFEST_DATA.toBytes(), result.getValue().getManifest().toBytes()); assertNotNull(result.getValue().getManifest().toObject(OciImageManifest.class)); assertEquals(ManifestMediaType.DOCKER_MANIFEST, result.getValue().getManifestMediaType()); } @SyncAsyncTest public void getManifestWithOciIndexType() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(OCI_INDEX, OCI_INDEX_DIGEST, OCI_INDEX_MEDIA_TYPE)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(OCI_INDEX, OCI_INDEX_DIGEST, OCI_INDEX_MEDIA_TYPE)); Response<GetManifestResult> result = SyncAsyncExtension.execute( () -> client.getManifestWithResponse(OCI_INDEX_DIGEST, Context.NONE), () -> asyncClient.getManifestWithResponse(OCI_INDEX_DIGEST)); assertArrayEquals(OCI_INDEX.toBytes(), result.getValue().getManifest().toBytes()); assertEquals(OCI_INDEX_MEDIA_TYPE, result.getValue().getManifestMediaType()); } @SyncAsyncTest public void downloadBlobOneChunk() throws IOException { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); SyncAsyncExtension.execute( () -> client.downloadStream(SMALL_CONTENT_SHA256, Channels.newChannel(stream)), () -> asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), stream))); stream.flush(); assertArrayEquals(SMALL_CONTENT.toBytes(), stream.toByteArray()); } @SyncAsyncTest public void downloadBlobMultipleChunks() throws IOException { BinaryData content = getDataSync((int) (CHUNK_SIZE * 2.3), sha256); String expectedDigest = "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(content, expectedDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(content, expectedDigest)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); WritableByteChannel channel = Channels.newChannel(stream); SyncAsyncExtension.execute( () -> client.downloadStream(expectedDigest, Channels.newChannel(stream)), () -> asyncClient.downloadStream(expectedDigest) .flatMap(result -> FluxUtil.writeToWritableByteChannel(result.toFluxByteBuffer(), channel))); stream.flush(); assertArrayEquals(content.toBytes(), stream.toByteArray()); } @SyncAsyncTest public void uploadBlobSmall() { BinaryData content = getDataSync((int) (CHUNK_SIZE * 0.1), sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(content), () -> asyncClient.uploadBlob(content)); } @SyncAsyncTest public void uploadBlobSmallChunks() { Flux<ByteBuffer> content = getDataAsync(CHUNK_SIZE * 2, CHUNK_SIZE / 10, sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromFlux(content).block()), () -> asyncClient.uploadBlob(content)); } @SyncAsyncTest public void uploadBlobBigChunks() { Flux<ByteBuffer> content = getDataAsync(CHUNK_SIZE * 2, (int) (CHUNK_SIZE * 1.5), sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromFlux(content).block()), () -> asyncClient.uploadBlob(content)); } private ByteBuffer slice(ByteBuffer buffer, int offset, int length) { Buffer limited = buffer.duplicate().position(offset).limit(offset + length); return (ByteBuffer) limited; } @Test public void uploadVariableChunkSize() { ByteBuffer buf = ByteBuffer.wrap(CHUNK); Flux<ByteBuffer> content = Flux.create(sink -> { sink.next(slice(buf, 0, 1)); sink.next(slice(buf, 1, 100)); sink.next(slice(buf, 101, 1000)); sink.complete(); }); ByteBuffer full = slice(buf, 0, 1101); sha256.update(full.asReadOnlyBuffer()); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); StepVerifier.create(asyncClient.uploadBlob(content)) .expectNextCount(1) .verifyComplete(); } @Test public void uploadFailWhileReadingInput() { Flux<ByteBuffer> content = Flux.create(sink -> { byte[] data = new byte[100]; new Random().nextBytes(data); sink.next(ByteBuffer.wrap(data)); sink.error(new IllegalStateException("foo")); }); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(() -> "foo")); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(() -> "foo")); assertThrows(IllegalStateException.class, () -> client.uploadBlob(BinaryData.fromFlux(content).block())); StepVerifier.create(asyncClient.uploadBlob(content)) .expectError(IllegalStateException.class) .verify(); } @Test public void uploadFromFile() throws IOException { File input = File.createTempFile("temp", "in"); Files.write(input.toPath(), CHUNK, StandardOpenOption.APPEND); sha256.update(CHUNK); byte[] secondChunk = Arrays.copyOfRange(CHUNK, 0, 100); Files.write(input.toPath(), secondChunk, StandardOpenOption.APPEND); sha256.update(secondChunk); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); StepVerifier.create(asyncClient.uploadBlob(BinaryData.fromFile(input.toPath()))) .expectNextCount(1) .verifyComplete(); } @SyncAsyncTest public void uploadFromStream() throws IOException { ByteBuffer data = slice(ByteBuffer.wrap(CHUNK), 0, 1024 * 100); sha256.update(data.asReadOnlyBuffer()); try (ByteBufferBackedInputStream stream = new ByteBufferBackedInputStream(data)) { Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromStream(stream)), () -> asyncClient.uploadBlob(BinaryData.fromStream(stream))); } } @SyncAsyncTest private void assertAcrException(HttpResponseException ex, String code) { assertInstanceOf(ResponseError.class, ex.getValue()); ResponseError error = (ResponseError) ex.getValue(); assertEquals(code, error.getCode()); } @Test public void downloadToFile() throws IOException { File output = File.createTempFile("temp", "in"); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); try (FileOutputStream outputStream = new FileOutputStream(output)) { StepVerifier.create(asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), outputStream))) .verifyComplete(); outputStream.flush(); assertArrayEquals(SMALL_CONTENT.toBytes(), Files.readAllBytes(output.toPath())); } } public static HttpClient createDownloadContentClient(BinaryData content, String digest) { try (InputStream contentStream = content.toStream()) { AtomicLong expectedStartPosition = new AtomicLong(0); long contentLength = content.getLength(); return new MockHttpClient(request -> { long start = expectedStartPosition.get(); long end = Math.min(start + CHUNK_SIZE, contentLength); if (start >= contentLength) { fail("Got download chunk on completed blob"); } HttpRange expectedRange = new HttpRange(start, (long) CHUNK_SIZE); assertEquals(expectedRange.toString(), request.getHeaders().getValue(HttpHeaderName.RANGE)); byte[] response = new byte[(int) (end - start)]; try { contentStream.read(response); } catch (IOException e) { fail(e); } HttpHeaders headers = new HttpHeaders() .add("Content-Range", String.format("bytes %s-%s/%s", start, end, contentLength)) .add(UtilsImpl.DOCKER_DIGEST_HEADER_NAME, digest); expectedStartPosition.set(start + CHUNK_SIZE); return new MockHttpResponse(request, 206, headers, response); }); } catch (IOException e) { fail(e); throw new RuntimeException(e); } } public static HttpClient createClientManifests(BinaryData content, String digest, ManifestMediaType returnContentType) { return new MockHttpClient(request -> { assertEquals(DEFAULT_MANIFEST_CONTENT_TYPE, request.getHeaders().getValue(HttpHeaderName.ACCEPT)); HttpHeaders headers = new HttpHeaders() .add(UtilsImpl.DOCKER_DIGEST_HEADER_NAME, digest) .add(HttpHeaderName.CONTENT_TYPE, returnContentType == null ? ManifestMediaType.OCI_MANIFEST.toString() : returnContentType.toString()); return new MockHttpResponse(request, 200, headers, content.toBytes()); }); } public static HttpClient createUploadContentClient(Supplier<String> calculateDigest, BiFunction<HttpRequest, Integer, HttpResponse> onChunk) { AtomicInteger callNumber = new AtomicInteger(); return new MockHttpClient(request -> { String expectedReceivedLocation = String.valueOf(callNumber.getAndIncrement()); HttpHeaders responseHeaders = new HttpHeaders().add("Location", String.valueOf(callNumber.get())); if (request.getHttpMethod() == HttpMethod.POST) { assertEquals(0, callNumber.get() - 1); return new MockHttpResponse(request, 202, responseHeaders); } else if (request.getHttpMethod() == HttpMethod.PATCH) { assertEquals("/" + expectedReceivedLocation, request.getUrl().getPath()); HttpResponse response = onChunk.apply(request, callNumber.get()); if (response == null) { response = new MockHttpResponse(request, 202, responseHeaders); } return response; } else if (request.getHttpMethod() == HttpMethod.PUT) { String expectedDigest = calculateDigest.get(); try { assertEquals(request.getUrl().getQuery(), "digest=" + URLEncoder.encode(expectedDigest, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { fail(e); } assertEquals("/" + expectedReceivedLocation, request.getUrl().getPath()); responseHeaders.add(DOCKER_DIGEST_HEADER_NAME, expectedDigest); return new MockHttpResponse(request, 201, responseHeaders); } return new MockHttpResponse(request, 404); }); } public static HttpClient createUploadContentClient(Supplier<String> calculateDigest) { return createUploadContentClient(calculateDigest, (r, c) -> null); } private BinaryData getDataSync(int size, MessageDigest sha256) { return BinaryData.fromFlux(getDataAsync(size, CHUNK_SIZE, sha256)).block(); } private Flux<ByteBuffer> getDataAsync(long size, int chunkSize, MessageDigest sha256) { return Flux.create(sink -> { long sent = 0; while (sent < size) { ByteBuffer buffer = ByteBuffer.wrap(CHUNK); if (sent + chunkSize > size) { buffer.limit((int) (size - sent)); } sha256.update(buffer.asReadOnlyBuffer()); sink.next(buffer); sent += chunkSize; } sink.complete(); }); } private ContainerRegistryContentClient createSyncClient(HttpClient httpClient) { return new ContainerRegistryContentClientBuilder() .endpoint("https: .repositoryName("foo") .httpClient(httpClient) .buildClient(); } private ContainerRegistryContentAsyncClient createAsyncClient(HttpClient httpClient) { return new ContainerRegistryContentClientBuilder() .endpoint("https: .repositoryName("foo") .httpClient(httpClient) .buildAsyncClient(); } static class MockHttpClient implements HttpClient { private final Function<HttpRequest, HttpResponse> requestToResponse; MockHttpClient(Function<HttpRequest, HttpResponse> requestToResponse) { this.requestToResponse = requestToResponse; } @Override public Mono<HttpResponse> send(HttpRequest httpRequest) { return Mono.just(requestToResponse.apply(httpRequest)); } @Override public HttpResponse sendSync(HttpRequest httpRequest, Context context) { return requestToResponse.apply(httpRequest); } } }
I'm not testing it - we're logging error responses in core for all failures.
public void uploadFails() { Flux<ByteBuffer> flux = Flux.create(sink -> { sha256.update(CHUNK); sink.next(ByteBuffer.wrap(CHUNK)); sha256.update(CHUNK); sink.next(ByteBuffer.wrap(CHUNK)); sink.complete(); }); BiFunction<HttpRequest, Integer, HttpResponse> onChunk = (r, c) -> { if (c == 3) { HttpHeaders responseHeaders = new HttpHeaders().add("Content-Type", String.valueOf("application/json")); String error = "{\"errors\":[{\"code\":\"BLOB_UPLOAD_INVALID\",\"message\":\"blob upload invalid\"}, {\"code\":\"BLOB_UPLOAD_FOO\",\"message\":\"blob upload foo\"}]}"; return new MockHttpResponse(r, 404, responseHeaders, error.getBytes(StandardCharsets.UTF_8)); } return null; }; Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); BinaryData content = BinaryData.fromFlux(flux, (long) CHUNK_SIZE * 2, false).block(); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest, onChunk)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest, onChunk)); ResourceNotFoundException ex = assertThrows(ResourceNotFoundException.class, () -> SyncAsyncExtension.execute( () -> client.uploadBlob(content), () -> asyncClient.uploadBlob(content))); assertAcrException(ex, "BLOB_UPLOAD_INVALID"); }
String error = "{\"errors\":[{\"code\":\"BLOB_UPLOAD_INVALID\",\"message\":\"blob upload invalid\"}, {\"code\":\"BLOB_UPLOAD_FOO\",\"message\":\"blob upload foo\"}]}";
public void uploadFails() { Flux<ByteBuffer> flux = Flux.create(sink -> { sha256.update(CHUNK); sink.next(ByteBuffer.wrap(CHUNK)); sha256.update(CHUNK); sink.next(ByteBuffer.wrap(CHUNK)); sink.complete(); }); BiFunction<HttpRequest, Integer, HttpResponse> onChunk = (r, c) -> { if (c == 3) { HttpHeaders responseHeaders = new HttpHeaders().add("Content-Type", String.valueOf("application/json")); String error = "{\"errors\":[{\"code\":\"BLOB_UPLOAD_INVALID\",\"message\":\"blob upload invalid\"}, {\"code\":\"BLOB_UPLOAD_FOO\",\"message\":\"blob upload foo\"}]}"; return new MockHttpResponse(r, 404, responseHeaders, error.getBytes(StandardCharsets.UTF_8)); } return null; }; Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); BinaryData content = BinaryData.fromFlux(flux, (long) CHUNK_SIZE * 2, false).block(); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest, onChunk)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest, onChunk)); ResourceNotFoundException ex = assertThrows(ResourceNotFoundException.class, () -> SyncAsyncExtension.execute( () -> client.uploadBlob(content), () -> asyncClient.uploadBlob(content))); assertAcrException(ex, "BLOB_UPLOAD_INVALID"); }
class ContainerRegistryContentClientTests { private static final BinaryData SMALL_CONTENT = BinaryData.fromString("foobar"); private static final String SMALL_CONTENT_SHA256 = "sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"; private static final String DEFAULT_MANIFEST_CONTENT_TYPE = "*/*," + ManifestMediaType.OCI_MANIFEST + "," + ManifestMediaType.DOCKER_MANIFEST + ",application/vnd.oci.image.index.v1+json" + ",application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.cncf.oras.artifact.manifest.v1+json"; private static final BinaryData MANIFEST_DATA = BinaryData.fromObject(MANIFEST); private static final BinaryData OCI_INDEX = BinaryData.fromString("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\"," + "\"manifests\":[{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"size\":7143,\"digest\":\"sha256:e692418e4cbaf90ca69d05a66403747baa33ee08806650b51fab815ad7fc331f\"," + "\"platform\":{\"architecture\":\"ppc64le\",\"os\":\"linux\"}}]}"); private static final String OCI_INDEX_DIGEST = "sha256:226bb568af1e417421f2f8053cd2847bdb5fcc52c7ed93823abdb595881c2b02"; private static final Random RANDOM = new Random(42); private static final byte[] CHUNK = new byte[CHUNK_SIZE]; static { RANDOM.nextBytes(CHUNK); } private MessageDigest sha256; @BeforeEach void beforeEach() { try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { fail(e); } } @Test public void downloadBlobWrongDigestInHeaderSync() { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); assertThrows(ServiceResponseException.class, () -> client.downloadStream("some-digest", Channels.newChannel(stream))); } @Test public void downloadManigestWrongDigestInHeaderSync() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); assertThrows(ServiceResponseException.class, () -> client.getManifest("latest")); } @Test public void downloadBlobWrongDigestInHeaderAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StepVerifier.create(asyncClient.downloadStream("some-digest") .flatMap(response -> FluxUtil.writeToOutputStream(response.toFluxByteBuffer(), stream))) .expectError(ServiceResponseException.class) .verify(); } @Test public void getManifestWrongDigestInHeaderAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); StepVerifier.create(asyncClient.getManifest("latest")) .expectError(ServiceResponseException.class) .verify(); } @Test public void downloadBlobWrongResponseSync() { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); assertThrows(ServiceResponseException.class, () -> client.downloadStream(SMALL_CONTENT_SHA256, Channels.newChannel(stream))); } @Test public void getManifestWrongResponseSync() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); assertThrows(ServiceResponseException.class, () -> client.getManifest("latest")); } @Test public void downloadBlobWrongResponseAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StepVerifier.create(asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(response -> FluxUtil.writeToOutputStream(response.toFluxByteBuffer(), stream))) .expectError(ServiceResponseException.class) .verify(); } @Test public void getManifestWrongResponseAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); StepVerifier.create(asyncClient.getManifest("latest")) .expectError(ServiceResponseException.class) .verify(); } @SyncAsyncTest public void getManifest() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, null)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, null)); GetManifestResult result = SyncAsyncExtension.execute( () -> client.getManifest(MANIFEST_DIGEST), () -> asyncClient.getManifest(MANIFEST_DIGEST)); assertArrayEquals(MANIFEST_DATA.toBytes(), result.getManifest().toBytes()); assertNotNull(result.getManifest().toObject(ManifestMediaType.class)); assertEquals(ManifestMediaType.OCI_MANIFEST, result.getManifestMediaType()); } @SyncAsyncTest public void getManifestWithDockerType() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, ManifestMediaType.DOCKER_MANIFEST)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, ManifestMediaType.DOCKER_MANIFEST)); Response<GetManifestResult> result = SyncAsyncExtension.execute( () -> client.getManifestWithResponse(MANIFEST_DIGEST, Context.NONE), () -> asyncClient.getManifestWithResponse(MANIFEST_DIGEST)); assertArrayEquals(MANIFEST_DATA.toBytes(), result.getValue().getManifest().toBytes()); assertNotNull(result.getValue().getManifest().toObject(OciImageManifest.class)); assertEquals(ManifestMediaType.DOCKER_MANIFEST, result.getValue().getManifestMediaType()); } @SyncAsyncTest public void getManifestWithOciIndexType() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(OCI_INDEX, OCI_INDEX_DIGEST, OCI_INDEX_MEDIA_TYPE)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(OCI_INDEX, OCI_INDEX_DIGEST, OCI_INDEX_MEDIA_TYPE)); Response<GetManifestResult> result = SyncAsyncExtension.execute( () -> client.getManifestWithResponse(OCI_INDEX_DIGEST, Context.NONE), () -> asyncClient.getManifestWithResponse(OCI_INDEX_DIGEST)); assertArrayEquals(OCI_INDEX.toBytes(), result.getValue().getManifest().toBytes()); assertEquals(OCI_INDEX_MEDIA_TYPE, result.getValue().getManifestMediaType()); } @SyncAsyncTest public void downloadBlobOneChunk() throws IOException { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); SyncAsyncExtension.execute( () -> client.downloadStream(SMALL_CONTENT_SHA256, Channels.newChannel(stream)), () -> asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), stream))); stream.flush(); assertArrayEquals(SMALL_CONTENT.toBytes(), stream.toByteArray()); } @SyncAsyncTest public void downloadBlobMultipleChunks() throws IOException { BinaryData content = getDataSync((int) (CHUNK_SIZE * 2.3), sha256); String expectedDigest = "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(content, expectedDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(content, expectedDigest)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); WritableByteChannel channel = Channels.newChannel(stream); SyncAsyncExtension.execute( () -> client.downloadStream(expectedDigest, Channels.newChannel(stream)), () -> asyncClient.downloadStream(expectedDigest) .flatMap(result -> FluxUtil.writeToWritableByteChannel(result.toFluxByteBuffer(), channel))); stream.flush(); assertArrayEquals(content.toBytes(), stream.toByteArray()); } @SyncAsyncTest public void uploadBlobSmall() { BinaryData content = getDataSync((int) (CHUNK_SIZE * 0.1), sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(content), () -> asyncClient.uploadBlob(content)); } @SyncAsyncTest public void uploadBlobSmallChunks() { Flux<ByteBuffer> content = getDataAsync(CHUNK_SIZE * 2, CHUNK_SIZE / 10, sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromFlux(content).block()), () -> asyncClient.uploadBlob(content)); } @SyncAsyncTest public void uploadBlobBigChunks() { Flux<ByteBuffer> content = getDataAsync(CHUNK_SIZE * 2, (int) (CHUNK_SIZE * 1.5), sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromFlux(content).block()), () -> asyncClient.uploadBlob(content)); } private ByteBuffer slice(ByteBuffer buffer, int offset, int length) { Buffer limited = buffer.duplicate().position(offset).limit(offset + length); return (ByteBuffer) limited; } @Test public void uploadVariableChunkSize() { ByteBuffer buf = ByteBuffer.wrap(CHUNK); Flux<ByteBuffer> content = Flux.create(sink -> { sink.next(slice(buf, 0, 1)); sink.next(slice(buf, 1, 100)); sink.next(slice(buf, 101, 1000)); sink.complete(); }); ByteBuffer full = slice(buf, 0, 1101); sha256.update(full.asReadOnlyBuffer()); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); StepVerifier.create(asyncClient.uploadBlob(content)) .expectNextCount(1) .verifyComplete(); } @Test public void uploadFailWhileReadingInput() { Flux<ByteBuffer> content = Flux.create(sink -> { byte[] data = new byte[100]; new Random().nextBytes(data); sink.next(ByteBuffer.wrap(data)); sink.error(new IllegalStateException("foo")); }); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(() -> "foo")); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(() -> "foo")); assertThrows(IllegalStateException.class, () -> client.uploadBlob(BinaryData.fromFlux(content).block())); StepVerifier.create(asyncClient.uploadBlob(content)) .expectError(IllegalStateException.class) .verify(); } @Test public void uploadFromFile() throws IOException { File input = File.createTempFile("temp", "in"); Files.write(input.toPath(), CHUNK, StandardOpenOption.APPEND); sha256.update(CHUNK); byte[] secondChunk = Arrays.copyOfRange(CHUNK, 0, 100); Files.write(input.toPath(), secondChunk, StandardOpenOption.APPEND); sha256.update(secondChunk); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); StepVerifier.create(asyncClient.uploadBlob(BinaryData.fromFile(input.toPath()))) .expectNextCount(1) .verifyComplete(); } @SyncAsyncTest public void uploadFromStream() throws IOException { ByteBuffer data = slice(ByteBuffer.wrap(CHUNK), 0, 1024 * 100); sha256.update(data.asReadOnlyBuffer()); try (ByteBufferBackedInputStream stream = new ByteBufferBackedInputStream(data)) { Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromStream(stream)), () -> asyncClient.uploadBlob(BinaryData.fromStream(stream))); } } @SyncAsyncTest private void assertAcrException(HttpResponseException ex, String code) { assertInstanceOf(ResponseError.class, ex.getValue()); ResponseError error = (ResponseError) ex.getValue(); assertEquals(code, error.getCode()); } @Test public void downloadToFile() throws IOException { File output = File.createTempFile("temp", "in"); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); try (FileOutputStream outputStream = new FileOutputStream(output)) { StepVerifier.create(asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), outputStream))) .verifyComplete(); outputStream.flush(); assertArrayEquals(SMALL_CONTENT.toBytes(), Files.readAllBytes(output.toPath())); } } public static HttpClient createDownloadContentClient(BinaryData content, String digest) { try (InputStream contentStream = content.toStream()) { AtomicLong expectedStartPosition = new AtomicLong(0); long contentLength = content.getLength(); return new MockHttpClient(request -> { long start = expectedStartPosition.get(); long end = Math.min(start + CHUNK_SIZE, contentLength); if (start >= contentLength) { fail("Got download chunk on completed blob"); } HttpRange expectedRange = new HttpRange(start, (long) CHUNK_SIZE); assertEquals(expectedRange.toString(), request.getHeaders().getValue(HttpHeaderName.RANGE)); byte[] response = new byte[(int) (end - start)]; try { contentStream.read(response); } catch (IOException e) { fail(e); } HttpHeaders headers = new HttpHeaders() .add("Content-Range", String.format("bytes %s-%s/%s", start, end, contentLength)) .add(UtilsImpl.DOCKER_DIGEST_HEADER_NAME, digest); expectedStartPosition.set(start + CHUNK_SIZE); return new MockHttpResponse(request, 206, headers, response); }); } catch (IOException e) { fail(e); throw new RuntimeException(e); } } public static HttpClient createClientManifests(BinaryData content, String digest, ManifestMediaType returnContentType) { return new MockHttpClient(request -> { assertEquals(DEFAULT_MANIFEST_CONTENT_TYPE, request.getHeaders().getValue(HttpHeaderName.ACCEPT)); HttpHeaders headers = new HttpHeaders() .add(UtilsImpl.DOCKER_DIGEST_HEADER_NAME, digest) .add(HttpHeaderName.CONTENT_TYPE, returnContentType == null ? ManifestMediaType.OCI_MANIFEST.toString() : returnContentType.toString()); return new MockHttpResponse(request, 200, headers, content.toBytes()); }); } public static HttpClient createUploadContentClient(Supplier<String> calculateDigest, BiFunction<HttpRequest, Integer, HttpResponse> onChunk) { AtomicInteger callNumber = new AtomicInteger(); return new MockHttpClient(request -> { String expectedReceivedLocation = String.valueOf(callNumber.getAndIncrement()); HttpHeaders responseHeaders = new HttpHeaders().add("Location", String.valueOf(callNumber.get())); if (request.getHttpMethod() == HttpMethod.POST) { assertEquals(0, callNumber.get() - 1); return new MockHttpResponse(request, 202, responseHeaders); } else if (request.getHttpMethod() == HttpMethod.PATCH) { assertEquals("/" + expectedReceivedLocation, request.getUrl().getPath()); HttpResponse response = onChunk.apply(request, callNumber.get()); if (response == null) { response = new MockHttpResponse(request, 202, responseHeaders); } return response; } else if (request.getHttpMethod() == HttpMethod.PUT) { String expectedDigest = calculateDigest.get(); try { assertEquals(request.getUrl().getQuery(), "digest=" + URLEncoder.encode(expectedDigest, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { fail(e); } assertEquals("/" + expectedReceivedLocation, request.getUrl().getPath()); responseHeaders.add(DOCKER_DIGEST_HEADER_NAME, expectedDigest); return new MockHttpResponse(request, 201, responseHeaders); } return new MockHttpResponse(request, 404); }); } public static HttpClient createUploadContentClient(Supplier<String> calculateDigest) { return createUploadContentClient(calculateDigest, (r, c) -> null); } private BinaryData getDataSync(int size, MessageDigest sha256) { return BinaryData.fromFlux(getDataAsync(size, CHUNK_SIZE, sha256)).block(); } private Flux<ByteBuffer> getDataAsync(long size, int chunkSize, MessageDigest sha256) { return Flux.create(sink -> { long sent = 0; while (sent < size) { ByteBuffer buffer = ByteBuffer.wrap(CHUNK); if (sent + chunkSize > size) { buffer.limit((int) (size - sent)); } sha256.update(buffer.asReadOnlyBuffer()); sink.next(buffer); sent += chunkSize; } sink.complete(); }); } private ContainerRegistryContentClient createSyncClient(HttpClient httpClient) { return new ContainerRegistryContentClientBuilder() .endpoint("https: .repositoryName("foo") .httpClient(httpClient) .buildClient(); } private ContainerRegistryContentAsyncClient createAsyncClient(HttpClient httpClient) { return new ContainerRegistryContentClientBuilder() .endpoint("https: .repositoryName("foo") .httpClient(httpClient) .buildAsyncClient(); } static class MockHttpClient implements HttpClient { private final Function<HttpRequest, HttpResponse> requestToResponse; MockHttpClient(Function<HttpRequest, HttpResponse> requestToResponse) { this.requestToResponse = requestToResponse; } @Override public Mono<HttpResponse> send(HttpRequest httpRequest) { return Mono.just(requestToResponse.apply(httpRequest)); } @Override public HttpResponse sendSync(HttpRequest httpRequest, Context context) { return requestToResponse.apply(httpRequest); } } }
class ContainerRegistryContentClientTests { private static final BinaryData SMALL_CONTENT = BinaryData.fromString("foobar"); private static final String SMALL_CONTENT_SHA256 = "sha256:c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2"; private static final String DEFAULT_MANIFEST_CONTENT_TYPE = "*/*," + ManifestMediaType.OCI_MANIFEST + "," + ManifestMediaType.DOCKER_MANIFEST + ",application/vnd.oci.image.index.v1+json" + ",application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.cncf.oras.artifact.manifest.v1+json"; private static final BinaryData MANIFEST_DATA = BinaryData.fromObject(MANIFEST); private static final BinaryData OCI_INDEX = BinaryData.fromString("{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\"," + "\"manifests\":[{\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\",\"size\":7143,\"digest\":\"sha256:e692418e4cbaf90ca69d05a66403747baa33ee08806650b51fab815ad7fc331f\"," + "\"platform\":{\"architecture\":\"ppc64le\",\"os\":\"linux\"}}]}"); private static final String OCI_INDEX_DIGEST = "sha256:226bb568af1e417421f2f8053cd2847bdb5fcc52c7ed93823abdb595881c2b02"; private static final Random RANDOM = new Random(42); private static final byte[] CHUNK = new byte[CHUNK_SIZE]; static { RANDOM.nextBytes(CHUNK); } private MessageDigest sha256; @BeforeEach void beforeEach() { try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { fail(e); } } @Test public void downloadBlobWrongDigestInHeaderSync() { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); assertThrows(ServiceResponseException.class, () -> client.downloadStream("some-digest", Channels.newChannel(stream))); } @Test public void downloadManigestWrongDigestInHeaderSync() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); assertThrows(ServiceResponseException.class, () -> client.getManifest("latest")); } @Test public void downloadBlobWrongDigestInHeaderAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StepVerifier.create(asyncClient.downloadStream("some-digest") .flatMap(response -> FluxUtil.writeToOutputStream(response.toFluxByteBuffer(), stream))) .expectError(ServiceResponseException.class) .verify(); } @Test public void getManifestWrongDigestInHeaderAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); StepVerifier.create(asyncClient.getManifest("latest")) .expectError(ServiceResponseException.class) .verify(); } @Test public void downloadBlobWrongResponseSync() { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); assertThrows(ServiceResponseException.class, () -> client.downloadStream(SMALL_CONTENT_SHA256, Channels.newChannel(stream))); } @Test public void getManifestWrongResponseSync() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); assertThrows(ServiceResponseException.class, () -> client.getManifest("latest")); } @Test public void downloadBlobWrongResponseAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, DIGEST_UNKNOWN)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StepVerifier.create(asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(response -> FluxUtil.writeToOutputStream(response.toFluxByteBuffer(), stream))) .expectError(ServiceResponseException.class) .verify(); } @Test public void getManifestWrongResponseAsync() { ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, DIGEST_UNKNOWN, null)); StepVerifier.create(asyncClient.getManifest("latest")) .expectError(ServiceResponseException.class) .verify(); } @SyncAsyncTest public void getManifest() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, null)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, null)); GetManifestResult result = SyncAsyncExtension.execute( () -> client.getManifest(MANIFEST_DIGEST), () -> asyncClient.getManifest(MANIFEST_DIGEST)); assertArrayEquals(MANIFEST_DATA.toBytes(), result.getManifest().toBytes()); assertNotNull(result.getManifest().toObject(ManifestMediaType.class)); assertEquals(ManifestMediaType.OCI_MANIFEST, result.getManifestMediaType()); } @SyncAsyncTest public void getManifestWithDockerType() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, ManifestMediaType.DOCKER_MANIFEST)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(MANIFEST_DATA, MANIFEST_DIGEST, ManifestMediaType.DOCKER_MANIFEST)); Response<GetManifestResult> result = SyncAsyncExtension.execute( () -> client.getManifestWithResponse(MANIFEST_DIGEST, Context.NONE), () -> asyncClient.getManifestWithResponse(MANIFEST_DIGEST)); assertArrayEquals(MANIFEST_DATA.toBytes(), result.getValue().getManifest().toBytes()); assertNotNull(result.getValue().getManifest().toObject(OciImageManifest.class)); assertEquals(ManifestMediaType.DOCKER_MANIFEST, result.getValue().getManifestMediaType()); } @SyncAsyncTest public void getManifestWithOciIndexType() { ContainerRegistryContentClient client = createSyncClient(createClientManifests(OCI_INDEX, OCI_INDEX_DIGEST, OCI_INDEX_MEDIA_TYPE)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createClientManifests(OCI_INDEX, OCI_INDEX_DIGEST, OCI_INDEX_MEDIA_TYPE)); Response<GetManifestResult> result = SyncAsyncExtension.execute( () -> client.getManifestWithResponse(OCI_INDEX_DIGEST, Context.NONE), () -> asyncClient.getManifestWithResponse(OCI_INDEX_DIGEST)); assertArrayEquals(OCI_INDEX.toBytes(), result.getValue().getManifest().toBytes()); assertEquals(OCI_INDEX_MEDIA_TYPE, result.getValue().getManifestMediaType()); } @SyncAsyncTest public void downloadBlobOneChunk() throws IOException { ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); SyncAsyncExtension.execute( () -> client.downloadStream(SMALL_CONTENT_SHA256, Channels.newChannel(stream)), () -> asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), stream))); stream.flush(); assertArrayEquals(SMALL_CONTENT.toBytes(), stream.toByteArray()); } @SyncAsyncTest public void downloadBlobMultipleChunks() throws IOException { BinaryData content = getDataSync((int) (CHUNK_SIZE * 2.3), sha256); String expectedDigest = "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createDownloadContentClient(content, expectedDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(content, expectedDigest)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); WritableByteChannel channel = Channels.newChannel(stream); SyncAsyncExtension.execute( () -> client.downloadStream(expectedDigest, Channels.newChannel(stream)), () -> asyncClient.downloadStream(expectedDigest) .flatMap(result -> FluxUtil.writeToWritableByteChannel(result.toFluxByteBuffer(), channel))); stream.flush(); assertArrayEquals(content.toBytes(), stream.toByteArray()); } @SyncAsyncTest public void uploadBlobSmall() { BinaryData content = getDataSync((int) (CHUNK_SIZE * 0.1), sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(content), () -> asyncClient.uploadBlob(content)); } @SyncAsyncTest public void uploadBlobSmallChunks() { Flux<ByteBuffer> content = getDataAsync(CHUNK_SIZE * 2, CHUNK_SIZE / 10, sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromFlux(content).block()), () -> asyncClient.uploadBlob(content)); } @SyncAsyncTest public void uploadBlobBigChunks() { Flux<ByteBuffer> content = getDataAsync(CHUNK_SIZE * 2, (int) (CHUNK_SIZE * 1.5), sha256); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromFlux(content).block()), () -> asyncClient.uploadBlob(content)); } private ByteBuffer slice(ByteBuffer buffer, int offset, int length) { Buffer limited = buffer.duplicate().position(offset).limit(offset + length); return (ByteBuffer) limited; } @Test public void uploadVariableChunkSize() { ByteBuffer buf = ByteBuffer.wrap(CHUNK); Flux<ByteBuffer> content = Flux.create(sink -> { sink.next(slice(buf, 0, 1)); sink.next(slice(buf, 1, 100)); sink.next(slice(buf, 101, 1000)); sink.complete(); }); ByteBuffer full = slice(buf, 0, 1101); sha256.update(full.asReadOnlyBuffer()); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); StepVerifier.create(asyncClient.uploadBlob(content)) .expectNextCount(1) .verifyComplete(); } @Test public void uploadFailWhileReadingInput() { Flux<ByteBuffer> content = Flux.create(sink -> { byte[] data = new byte[100]; new Random().nextBytes(data); sink.next(ByteBuffer.wrap(data)); sink.error(new IllegalStateException("foo")); }); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(() -> "foo")); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(() -> "foo")); assertThrows(IllegalStateException.class, () -> client.uploadBlob(BinaryData.fromFlux(content).block())); StepVerifier.create(asyncClient.uploadBlob(content)) .expectError(IllegalStateException.class) .verify(); } @Test public void uploadFromFile() throws IOException { File input = File.createTempFile("temp", "in"); Files.write(input.toPath(), CHUNK, StandardOpenOption.APPEND); sha256.update(CHUNK); byte[] secondChunk = Arrays.copyOfRange(CHUNK, 0, 100); Files.write(input.toPath(), secondChunk, StandardOpenOption.APPEND); sha256.update(secondChunk); Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); StepVerifier.create(asyncClient.uploadBlob(BinaryData.fromFile(input.toPath()))) .expectNextCount(1) .verifyComplete(); } @SyncAsyncTest public void uploadFromStream() throws IOException { ByteBuffer data = slice(ByteBuffer.wrap(CHUNK), 0, 1024 * 100); sha256.update(data.asReadOnlyBuffer()); try (ByteBufferBackedInputStream stream = new ByteBufferBackedInputStream(data)) { Supplier<String> calculateDigest = () -> "sha256:" + bytesToHexString(sha256.digest()); ContainerRegistryContentClient client = createSyncClient(createUploadContentClient(calculateDigest)); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createUploadContentClient(calculateDigest)); SyncAsyncExtension.execute( () -> client.uploadBlob(BinaryData.fromStream(stream)), () -> asyncClient.uploadBlob(BinaryData.fromStream(stream))); } } @SyncAsyncTest private void assertAcrException(HttpResponseException ex, String code) { assertInstanceOf(ResponseError.class, ex.getValue()); ResponseError error = (ResponseError) ex.getValue(); assertEquals(code, error.getCode()); } @Test public void downloadToFile() throws IOException { File output = File.createTempFile("temp", "in"); ContainerRegistryContentAsyncClient asyncClient = createAsyncClient(createDownloadContentClient(SMALL_CONTENT, SMALL_CONTENT_SHA256)); try (FileOutputStream outputStream = new FileOutputStream(output)) { StepVerifier.create(asyncClient.downloadStream(SMALL_CONTENT_SHA256) .flatMap(result -> FluxUtil.writeToOutputStream(result.toFluxByteBuffer(), outputStream))) .verifyComplete(); outputStream.flush(); assertArrayEquals(SMALL_CONTENT.toBytes(), Files.readAllBytes(output.toPath())); } } public static HttpClient createDownloadContentClient(BinaryData content, String digest) { try (InputStream contentStream = content.toStream()) { AtomicLong expectedStartPosition = new AtomicLong(0); long contentLength = content.getLength(); return new MockHttpClient(request -> { long start = expectedStartPosition.get(); long end = Math.min(start + CHUNK_SIZE, contentLength); if (start >= contentLength) { fail("Got download chunk on completed blob"); } HttpRange expectedRange = new HttpRange(start, (long) CHUNK_SIZE); assertEquals(expectedRange.toString(), request.getHeaders().getValue(HttpHeaderName.RANGE)); byte[] response = new byte[(int) (end - start)]; try { contentStream.read(response); } catch (IOException e) { fail(e); } HttpHeaders headers = new HttpHeaders() .add("Content-Range", String.format("bytes %s-%s/%s", start, end, contentLength)) .add(UtilsImpl.DOCKER_DIGEST_HEADER_NAME, digest); expectedStartPosition.set(start + CHUNK_SIZE); return new MockHttpResponse(request, 206, headers, response); }); } catch (IOException e) { fail(e); throw new RuntimeException(e); } } public static HttpClient createClientManifests(BinaryData content, String digest, ManifestMediaType returnContentType) { return new MockHttpClient(request -> { assertEquals(DEFAULT_MANIFEST_CONTENT_TYPE, request.getHeaders().getValue(HttpHeaderName.ACCEPT)); HttpHeaders headers = new HttpHeaders() .add(UtilsImpl.DOCKER_DIGEST_HEADER_NAME, digest) .add(HttpHeaderName.CONTENT_TYPE, returnContentType == null ? ManifestMediaType.OCI_MANIFEST.toString() : returnContentType.toString()); return new MockHttpResponse(request, 200, headers, content.toBytes()); }); } public static HttpClient createUploadContentClient(Supplier<String> calculateDigest, BiFunction<HttpRequest, Integer, HttpResponse> onChunk) { AtomicInteger callNumber = new AtomicInteger(); return new MockHttpClient(request -> { String expectedReceivedLocation = String.valueOf(callNumber.getAndIncrement()); HttpHeaders responseHeaders = new HttpHeaders().add("Location", String.valueOf(callNumber.get())); if (request.getHttpMethod() == HttpMethod.POST) { assertEquals(0, callNumber.get() - 1); return new MockHttpResponse(request, 202, responseHeaders); } else if (request.getHttpMethod() == HttpMethod.PATCH) { assertEquals("/" + expectedReceivedLocation, request.getUrl().getPath()); HttpResponse response = onChunk.apply(request, callNumber.get()); if (response == null) { response = new MockHttpResponse(request, 202, responseHeaders); } return response; } else if (request.getHttpMethod() == HttpMethod.PUT) { String expectedDigest = calculateDigest.get(); try { assertEquals(request.getUrl().getQuery(), "digest=" + URLEncoder.encode(expectedDigest, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { fail(e); } assertEquals("/" + expectedReceivedLocation, request.getUrl().getPath()); responseHeaders.add(DOCKER_DIGEST_HEADER_NAME, expectedDigest); return new MockHttpResponse(request, 201, responseHeaders); } return new MockHttpResponse(request, 404); }); } public static HttpClient createUploadContentClient(Supplier<String> calculateDigest) { return createUploadContentClient(calculateDigest, (r, c) -> null); } private BinaryData getDataSync(int size, MessageDigest sha256) { return BinaryData.fromFlux(getDataAsync(size, CHUNK_SIZE, sha256)).block(); } private Flux<ByteBuffer> getDataAsync(long size, int chunkSize, MessageDigest sha256) { return Flux.create(sink -> { long sent = 0; while (sent < size) { ByteBuffer buffer = ByteBuffer.wrap(CHUNK); if (sent + chunkSize > size) { buffer.limit((int) (size - sent)); } sha256.update(buffer.asReadOnlyBuffer()); sink.next(buffer); sent += chunkSize; } sink.complete(); }); } private ContainerRegistryContentClient createSyncClient(HttpClient httpClient) { return new ContainerRegistryContentClientBuilder() .endpoint("https: .repositoryName("foo") .httpClient(httpClient) .buildClient(); } private ContainerRegistryContentAsyncClient createAsyncClient(HttpClient httpClient) { return new ContainerRegistryContentClientBuilder() .endpoint("https: .repositoryName("foo") .httpClient(httpClient) .buildAsyncClient(); } static class MockHttpClient implements HttpClient { private final Function<HttpRequest, HttpResponse> requestToResponse; MockHttpClient(Function<HttpRequest, HttpResponse> requestToResponse) { this.requestToResponse = requestToResponse; } @Override public Mono<HttpResponse> send(HttpRequest httpRequest) { return Mono.just(requestToResponse.apply(httpRequest)); } @Override public HttpResponse sendSync(HttpRequest httpRequest, Context context) { return requestToResponse.apply(httpRequest); } } }
nit: make this a shared method so sync and async don't diverge accidentally
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (applyTimeout) { UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); urlBuilder.setQueryParameter("timeout", timeoutInSeconds); context.getHttpRequest().setUrl(urlBuilder.toString()); } return next.process(); }
}
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (applyTimeout) { String httpRequest = setTimeoutParameter(context, timeoutInSeconds); context.getHttpRequest().setUrl(httpRequest); } return next.process(); }
class ServiceTimeoutPolicy implements HttpPipelinePolicy { private final boolean applyTimeout; private final String timeoutInSeconds; /** * Creates a service timeout policy. * <p> * The maximum timeout interval for Blob service operations is 30 seconds, with exceptions for certain operations. * The default value is also 30 seconds, although some read and write operations may use a larger default. Apart * from these exceptions, the Blob service automatically reduces any timeouts larger than 30 seconds to the * 30-second maximum. For more information, see here: * <a href="https: * * @param timeout The timeout duration. */ public ServiceTimeoutPolicy(Duration timeout) { if (timeout == null) { applyTimeout = false; timeoutInSeconds = null; } else { long tempTimeoutInSeconds = timeout.getSeconds(); if (tempTimeoutInSeconds <= 0) { applyTimeout = false; timeoutInSeconds = null; } else { applyTimeout = true; timeoutInSeconds = String.valueOf(tempTimeoutInSeconds); } } } @Override @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { if (applyTimeout) { UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); urlBuilder.setQueryParameter("timeout", timeoutInSeconds); context.getHttpRequest().setUrl(urlBuilder.toString()); } return next.processSync(); } /** * Gets the position to place the policy. * * @return The position to place the policy. */ public HttpPipelinePosition getPipelinePosition() { return HttpPipelinePosition.PER_CALL; } }
class ServiceTimeoutPolicy implements HttpPipelinePolicy { private final boolean applyTimeout; private final String timeoutInSeconds; /** * Creates a service timeout policy. * <p> * The maximum timeout interval for Blob service operations is 30 seconds, with exceptions for certain operations. * The default value is also 30 seconds, although some read and write operations may use a larger default. Apart * from these exceptions, the service automatically reduces any timeouts larger than 30 seconds to the * 30-second maximum. For more information, see here: * <a href="https: * For more information on setting timeouts for file shares, see here: * <a href="https: * For more information on setting timeouts on queues, see here: * <a href="https: * * @param timeout The timeout duration. */ public ServiceTimeoutPolicy(Duration timeout) { if (timeout == null) { applyTimeout = false; timeoutInSeconds = null; } else { long tempTimeoutInSeconds = timeout.getSeconds(); if (tempTimeoutInSeconds <= 0) { applyTimeout = false; timeoutInSeconds = null; } else { applyTimeout = true; timeoutInSeconds = String.valueOf(tempTimeoutInSeconds); } } } @Override @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { if (applyTimeout) { String httpRequest = setTimeoutParameter(context, timeoutInSeconds); context.getHttpRequest().setUrl(httpRequest); } return next.processSync(); } static String setTimeoutParameter(HttpPipelineCallContext context, String timeoutInSeconds) { UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); urlBuilder.setQueryParameter("timeout", timeoutInSeconds); return urlBuilder.toString(); } /** * Gets the position to place the policy. * * @return The position to place the policy. */ public HttpPipelinePosition getPipelinePosition() { return HttpPipelinePosition.PER_CALL; } }
We should not use sync poller in async client test. Let's investigate why async poller is flaky.
public void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); cancelCertificateOperationRunner((certName) -> { SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()).getSyncPoller(); certPoller.poll(); certPoller.cancelOperation(); certPoller.waitUntil(LongRunningOperationStatus.USER_CANCELLED); KeyVaultCertificateWithPolicy certificate = certPoller.getFinalResult(); assertFalse(certificate.getProperties().isEnabled()); certPoller.waitForCompletion(); }); }
SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller =
public void cancelCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); cancelCertificateOperationRunner((certName) -> { SyncPoller<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()).getSyncPoller(); certPoller.poll(); certPoller.cancelOperation(); certPoller.waitUntil(LongRunningOperationStatus.USER_CANCELLED); KeyVaultCertificateWithPolicy certificate = certPoller.getFinalResult(); assertFalse(certificate.getProperties().isEnabled()); certPoller.waitForCompletion(); }); }
class CertificateAsyncClientTest extends CertificateClientTestBase { private CertificateAsyncClient certificateAsyncClient; @Override protected void beforeTest() { beforeTestSetup(); } private void createCertificateAsyncClient(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion, null); } private void createCertificateAsyncClient(HttpClient httpClient, CertificateServiceVersion serviceVersion, String testTenantId) { HttpPipeline httpPipeline = getHttpPipeline(buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), testTenantId); CertificateClientImpl implClient = spy(new CertificateClientImpl(getEndpoint(), httpPipeline, serviceVersion)); if (interceptorManager.isPlaybackMode()) { when(implClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } certificateAsyncClient = new CertificateAsyncClient(implClient); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { BiFunction<HttpRequest, Context, Boolean> skipRequestFunction = (request, context) -> { String callerMethod = (String) context.getData("caller-method").orElse(""); return (callerMethod.contains("list") || callerMethod.contains("getCertificates") || callerMethod.contains("getCertificateVersions") || callerMethod.contains("delete") || callerMethod.contains("recover") || callerMethod.contains("setCertificateContacts") || callerMethod.contains("deleteCertificateContacts") || callerMethod.contains("getCertificateContacts") || callerMethod.contains("getCertificateIssuers")); }; return new AssertingHttpClientBuilder(httpClient) .skipRequest(skipRequestFunction) .assertAsync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); createCertificateRunner((certificatePolicy) -> { String certName = testResourceNamer.randomName("testCert", 25); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, certificatePolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expected -> { assertEquals(certName, expected.getName()); assertNotNull(expected.getProperties().getCreatedOn()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificateWithMultipleTenants(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); createCertificateRunner((certificatePolicy) -> { String certName = testResourceNamer.randomName("testCert", 20); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, certificatePolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expected -> { assertEquals(certName, expected.getName()); assertNotNull(expected.getProperties().getCreatedOn()); }).verifyComplete(); }); KeyVaultCredentialPolicy.clearCache(); createCertificateRunner((certificatePolicy) -> { String certName = testResourceNamer.randomName("testCert", 20); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, certificatePolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expected -> { assertEquals(certName, expected.getName()); assertNotNull(expected.getProperties().getCreatedOn()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginCreateCertificate("", CertificatePolicy.getDefault())) .verifyErrorSatisfies(e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginCreateCertificate(testResourceNamer.randomName("tempCert", 20), null)) .verifyErrorSatisfies(e -> assertEquals(NullPointerException.class, e.getClass())); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginCreateCertificate(null, null)) .verifyErrorSatisfies(e -> assertEquals(NullPointerException.class, e.getClass())); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); updateCertificateRunner((originalTags, updatedTags) -> { String certName = testResourceNamer.randomName("testCert", 20); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault(), true, originalTags); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(cert -> certificateAsyncClient .updateCertificateProperties(cert.getProperties().setTags(updatedTags)))) .assertNext(cert -> { validateMapResponse(updatedTags, cert.getProperties().getTags()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); updateDisabledCertificateRunner((originalTags, updatedTags) -> { String certName = testResourceNamer.randomName("testCert", 20); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault(), false, originalTags); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(cert -> certificateAsyncClient .updateCertificateProperties(cert.getProperties().setTags(updatedTags)))) .assertNext(cert -> { validateMapResponse(updatedTags, cert.getProperties().getTags()); assertFalse(cert.getProperties().isEnabled()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expectedCert -> certificateAsyncClient.getCertificate(certificateName) .map(returnedCert -> validatePolicy(expectedCert.getPolicy(), returnedCert.getPolicy()))) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificateSpecificVersionRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expectedCert -> certificateAsyncClient.getCertificateVersion(certificateName, expectedCert.getProperties().getVersion()) .map(returnedCert -> validateCertificate(expectedCert, returnedCert))) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.getCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); deleteCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(ignored -> certificateAsyncClient.beginDeleteCertificate(certificateName) .last().flatMap(asyncPollResponse -> Mono.defer(() -> Mono.just(asyncPollResponse.getValue()))) )) .assertNext(expectedCert -> { assertNotNull(expectedCert.getDeletedOn()); assertNotNull(expectedCert.getRecoveryId()); assertNotNull(expectedCert.getScheduledPurgeDate()); assertEquals(certificateName, expectedCert.getName()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginDeleteCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getDeletedCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(ignored -> certificateAsyncClient.beginDeleteCertificate(certificateName) .last().flatMap(asyncPollResponse -> Mono.just(asyncPollResponse.getValue())))) .assertNext(deletedCertificate -> { assertNotNull(deletedCertificate.getDeletedOn()); assertNotNull(deletedCertificate.getRecoveryId()); assertNotNull(deletedCertificate.getScheduledPurgeDate()); assertEquals(certificateName, deletedCertificate.getName()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.getDeletedCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); AtomicReference<KeyVaultCertificateWithPolicy> createdCertificate = new AtomicReference<>(); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(keyVaultCertificateWithPolicy -> { createdCertificate.set(keyVaultCertificateWithPolicy); return certificateAsyncClient.beginDeleteCertificate(certificateName) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(asyncPollResponse -> Mono.just(asyncPollResponse.getValue())); }) .flatMap(ignored -> certificateAsyncClient.beginRecoverDeletedCertificate(certificateName) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(certAsyncResponse -> Mono.just(certAsyncResponse.getValue())))) .assertNext(recoveredCert -> { assertEquals(certificateName, recoveredCert.getName()); validateCertificate(createdCertificate.get(), recoveredCert); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginRecoverDeletedCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); backupCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(ignored -> certificateAsyncClient.backupCertificate(certificateName))) .assertNext(backupBytes -> { assertNotNull(backupBytes); assertTrue(backupBytes.length > 0); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.backupCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); restoreCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); AtomicReference<KeyVaultCertificateWithPolicy> createdCertificate = new AtomicReference<>(); AtomicReference<Byte[]> backup = new AtomicReference<>(); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(keyVaultCertificateWithPolicy -> { createdCertificate.set(keyVaultCertificateWithPolicy); return certificateAsyncClient.backupCertificate(certificateName) .flatMap(backupBytes -> { Byte[] bytes = new Byte[backupBytes.length]; int i = 0; for (Byte bt : backupBytes) { bytes[i] = bt; i++; } backup.set(bytes); return Mono.just(backupBytes); }); })) .assertNext(backupBytes -> { assertNotNull(backupBytes); assertTrue(backupBytes.length > 0); }).verifyComplete(); StepVerifier.create(certificateAsyncClient.beginDeleteCertificate(certificateName) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().then(Mono.defer(() -> certificateAsyncClient.purgeDeletedCertificate(certificateName))) .then(Mono.just("complete"))) .assertNext(input -> assertEquals("complete", input)) .verifyComplete(); sleepInRecordMode(40000); StepVerifier.create(Mono.defer(() -> { byte[] backupBytes = new byte[backup.get().length]; for (int i = 0; i < backup.get().length; i++) { backupBytes[i] = backup.get()[i]; } return certificateAsyncClient.restoreCertificateBackup(backupBytes); })).assertNext(restoredCertificate -> { assertEquals(certificateName, restoredCertificate.getName()); validatePolicy(restoredCertificate.getPolicy(), createdCertificate.get().getPolicy()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificateOperationRunner((certificateName) -> { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, setupPolicy()); AtomicReference<KeyVaultCertificateWithPolicy> expectedCert = new AtomicReference<>(); StepVerifier.create( certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(keyVaultCertificateWithPolicy -> { expectedCert.set(keyVaultCertificateWithPolicy); return certificateAsyncClient.getCertificateOperation(certificateName) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult); })) .assertNext(retrievedCert -> { validateCertificate(expectedCert.get(), retrievedCert); validatePolicy(expectedCert.get().getPolicy(), retrievedCert.getPolicy()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); deleteCertificateOperationRunner((certificateName) -> { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, CertificatePolicy.getDefault()); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(ignored -> certificateAsyncClient.deleteCertificateOperation(certificateName))) .assertNext(certificateOperation -> { assertEquals("completed", certificateOperation.getStatus()); }).verifyComplete(); StepVerifier.create(certificateAsyncClient.deleteCertificateOperation(certificateName)) .verifyErrorSatisfies(e -> { assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificatePolicyRunner((certificateName) -> { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, setupPolicy()); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(certificate -> { validatePolicy(setupPolicy(), certificate.getPolicy()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); updateCertificatePolicyRunner((certificateName) -> { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, setupPolicy()); AtomicReference<KeyVaultCertificateWithPolicy> createdCert = new AtomicReference<>(); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(keyVaultCertificateWithPolicy -> { keyVaultCertificateWithPolicy.getPolicy().setExportable(false); createdCert.set(keyVaultCertificateWithPolicy); return certificateAsyncClient.updateCertificatePolicy(certificateName, keyVaultCertificateWithPolicy.getPolicy()); })) .assertNext(certificatePolicy -> validatePolicy(createdCert.get().getPolicy(), certificatePolicy)).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(certificateAsyncClient.restoreCertificateBackup(keyBackupBytes)) .verifyErrorSatisfies(e -> { assertResponseException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); listCertificatesRunner((certificatesToList) -> { HashSet<String> certificates = new HashSet<>(certificatesToList); for (String certName : certificates) { StepVerifier.create(certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED).last()) .assertNext(response -> assertNotNull(response.getValue())) .verifyComplete(); } StepVerifier.create(certificateAsyncClient.listPropertiesOfCertificates() .map(certificate -> { certificates.remove(certificate.getName()); return Mono.empty(); }).last()) .assertNext(ignore -> { assertEquals(0, certificates.size()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listPropertiesOfCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); listPropertiesOfCertificatesRunner((certificatesToList) -> { HashSet<String> certificates = new HashSet<>(certificatesToList); for (String certName : certificates) { StepVerifier.create(certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED).last()) .assertNext(response -> assertNotNull(response.getValue())) .verifyComplete(); } StepVerifier.create(certificateAsyncClient.listPropertiesOfCertificates(false) .map(certificate -> { certificates.remove(certificate.getName()); return Mono.empty(); }).last()) .assertNext(ignore -> { assertEquals(0, certificates.size()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); createIssuerRunner((issuer) -> { StepVerifier.create(certificateAsyncClient.createIssuer(issuer)) .assertNext(createdIssuer -> { assertTrue(issuerCreatedCorrectly(issuer, createdIssuer)); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createIssuerEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.createIssuer(new CertificateIssuer("", ""))) .verifyErrorSatisfies(e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createIssuerNullProvider(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.createIssuer(new CertificateIssuer("", null))) .verifyErrorSatisfies(e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.createIssuer(null)) .verifyErrorSatisfies(e -> assertEquals(NullPointerException.class, e.getClass())); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificateIssuerRunner((issuer) -> { AtomicReference<CertificateIssuer> certificateIssuer = new AtomicReference<>(); StepVerifier.create(certificateAsyncClient.createIssuer(issuer) .flatMap(createdIssuer -> { certificateIssuer.set(createdIssuer); return certificateAsyncClient.getIssuer(issuer.getName()); })) .assertNext(retrievedIssuer -> { assertTrue(issuerCreatedCorrectly(certificateIssuer.get(), retrievedIssuer)); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.backupCertificate("non-existing")) .verifyErrorSatisfies(e -> { assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); deleteCertificateIssuerRunner((issuer) -> { AtomicReference<CertificateIssuer> createdIssuer = new AtomicReference<>(); StepVerifier.create(certificateAsyncClient.createIssuer(issuer) .flatMap(certificateIssuer -> { createdIssuer.set(certificateIssuer); return certificateAsyncClient.deleteIssuer(issuer.getName()); })) .assertNext(deletedIssuer -> { assertTrue(issuerCreatedCorrectly(createdIssuer.get(), deletedIssuer)); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.backupCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); listCertificateIssuersRunner((certificateIssuers) -> { HashMap<String, CertificateIssuer> certificateIssuersToList = new HashMap<>(certificateIssuers); AtomicInteger count = new AtomicInteger(0); for (CertificateIssuer issuer : certificateIssuers.values()) { StepVerifier.create(certificateAsyncClient.createIssuer(issuer)) .assertNext(certificateIssuer -> { assertNotNull(certificateIssuer.getName()); }).verifyComplete(); } StepVerifier.create(certificateAsyncClient.listPropertiesOfIssuers() .map(issuerProperties -> { if (certificateIssuersToList.containsKey(issuerProperties.getName())) { count.incrementAndGet(); } return Mono.empty(); }).last()) .assertNext(ignore -> assertEquals(certificateIssuersToList.size(), count.get())) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); updateIssuerRunner((issuerToCreate, issuerToUpdate) -> { StepVerifier.create(certificateAsyncClient.createIssuer(issuerToCreate) .flatMap(createdIssuer -> certificateAsyncClient.updateIssuer(issuerToUpdate))) .assertNext(updatedIssuer -> assertTrue(issuerUpdatedCorrectly(issuerToCreate, updatedIssuer))).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); List<CertificateContact> contacts = Arrays.asList(setupContact()); StepVerifier.create(certificateAsyncClient.setContacts(contacts)) .assertNext(contact -> validateContact(setupContact(), contact)) .verifyComplete(); StepVerifier.create(certificateAsyncClient.deleteContacts().then(Mono.just("complete"))) .assertNext(input -> assertEquals("complete", input)).verifyComplete(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); List<CertificateContact> contacts = Arrays.asList(setupContact()); StepVerifier.create(certificateAsyncClient.setContacts(contacts)) .assertNext(contact -> validateContact(setupContact(), contact)) .verifyComplete(); sleepInRecordMode(6000); StepVerifier.create(certificateAsyncClient.listContacts()) .assertNext(contact -> validateContact(setupContact(), contact)) .verifyComplete(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); List<CertificateContact> contacts = Arrays.asList(setupContact()); StepVerifier.create(certificateAsyncClient.setContacts(contacts)) .assertNext(contact -> validateContact(setupContact(), contact)) .verifyComplete(); StepVerifier.create(certificateAsyncClient.deleteContacts()) .assertNext(contact -> { validateContact(setupContact(), contact); }).verifyComplete(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateOperationNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.getCertificateOperation("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.getCertificatePolicy("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); String certName = testResourceNamer.randomName("testListCertVersion", 25); int versionsToCreate = 5; for (int i = 0; i < versionsToCreate; i++) { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult).then(Mono.just("complete"))).assertNext(input -> assertEquals("complete", input)).verifyComplete(); } AtomicInteger createdVersions = new AtomicInteger(); StepVerifier.create(certificateAsyncClient.listPropertiesOfCertificateVersions(certName) .map(certificateProperties -> { createdVersions.getAndIncrement(); return Mono.just("complete"); }).last()).assertNext(ignored -> assertEquals(versionsToCreate, createdVersions.get())).verifyComplete(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); if (interceptorManager.isLiveMode()) { return; } listDeletedCertificatesRunner((certificates) -> { HashSet<String> certificatesToDelete = new HashSet<>(certificates); for (String certName : certificatesToDelete) { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED).last() .then(Mono.just("complete"))).assertNext(input -> assertEquals("complete", input)).verifyComplete(); } for (String certName : certificates) { PollerFlux<DeletedCertificate, Void> poller = certificateAsyncClient.beginDeleteCertificate(certName); StepVerifier.create(poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last()).assertNext(asyncPollResponse -> assertNotNull(asyncPollResponse.getValue())).verifyComplete(); } sleepInRecordMode(4000); StepVerifier.create(certificateAsyncClient.listDeletedCertificates() .map(deletedCertificate -> { certificatesToDelete.remove(deletedCertificate.getName()); return Mono.just("complete"); }).last()) .assertNext(ignored -> { assertEquals(0, certificatesToDelete.size()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); importCertificateRunner((importCertificateOptions) -> { StepVerifier.create(certificateAsyncClient.importCertificate(importCertificateOptions)) .assertNext(importedCertificate -> { assertTrue(toHexString(importedCertificate.getProperties().getX509Thumbprint()) .equalsIgnoreCase("db1497bc2c82b365c5c7c73f611513ee117790a9")); assertEquals(importCertificateOptions.isEnabled(), importedCertificate.getProperties().isEnabled()); X509Certificate x509Certificate = null; try { x509Certificate = loadCerToX509Certificate(importedCertificate); } catch (CertificateException | IOException e) { e.printStackTrace(); fail(); } assertEquals("CN=KeyVaultTest", x509Certificate.getSubjectX500Principal().getName()); assertEquals("CN=KeyVaultTest", x509Certificate.getIssuerX500Principal().getName()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.mergeCertificate( new MergeCertificateOptions(testResourceNamer.randomName("testCert", 20), Arrays.asList("test".getBytes())))) .verifyErrorSatisfies(e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException { createCertificateAsyncClient(httpClient, serviceVersion); importPemCertificateRunner((importCertificateOptions) -> { StepVerifier.create(certificateAsyncClient.importCertificate(importCertificateOptions)) .assertNext(importedCertificate -> { assertEquals(importCertificateOptions.isEnabled(), importedCertificate.getProperties().isEnabled()); assertEquals(CertificateContentType.PEM, importedCertificate.getPolicy().getContentType()); }).verifyComplete(); }); } }
class CertificateAsyncClientTest extends CertificateClientTestBase { private CertificateAsyncClient certificateAsyncClient; @Override protected void beforeTest() { beforeTestSetup(); } private void createCertificateAsyncClient(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion, null); } private void createCertificateAsyncClient(HttpClient httpClient, CertificateServiceVersion serviceVersion, String testTenantId) { HttpPipeline httpPipeline = getHttpPipeline(buildAsyncAssertingClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient), testTenantId); CertificateClientImpl implClient = spy(new CertificateClientImpl(getEndpoint(), httpPipeline, serviceVersion)); if (interceptorManager.isPlaybackMode()) { when(implClient.getDefaultPollingInterval()).thenReturn(Duration.ofMillis(10)); } certificateAsyncClient = new CertificateAsyncClient(implClient); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { BiFunction<HttpRequest, Context, Boolean> skipRequestFunction = (request, context) -> { String callerMethod = (String) context.getData("caller-method").orElse(""); return (callerMethod.contains("list") || callerMethod.contains("getCertificates") || callerMethod.contains("getCertificateVersions") || callerMethod.contains("delete") || callerMethod.contains("recover") || callerMethod.contains("setCertificateContacts") || callerMethod.contains("deleteCertificateContacts") || callerMethod.contains("getCertificateContacts") || callerMethod.contains("getCertificateIssuers")); }; return new AssertingHttpClientBuilder(httpClient) .skipRequest(skipRequestFunction) .assertAsync() .build(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); createCertificateRunner((certificatePolicy) -> { String certName = testResourceNamer.randomName("testCert", 25); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, certificatePolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expected -> { assertEquals(certName, expected.getName()); assertNotNull(expected.getProperties().getCreatedOn()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificateWithMultipleTenants(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion, testResourceNamer.randomUuid()); createCertificateRunner((certificatePolicy) -> { String certName = testResourceNamer.randomName("testCert", 20); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, certificatePolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expected -> { assertEquals(certName, expected.getName()); assertNotNull(expected.getProperties().getCreatedOn()); }).verifyComplete(); }); KeyVaultCredentialPolicy.clearCache(); createCertificateRunner((certificatePolicy) -> { String certName = testResourceNamer.randomName("testCert", 20); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, certificatePolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expected -> { assertEquals(certName, expected.getName()); assertNotNull(expected.getProperties().getCreatedOn()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificateEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginCreateCertificate("", CertificatePolicy.getDefault())) .verifyErrorSatisfies(e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificateNullPolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginCreateCertificate(testResourceNamer.randomName("tempCert", 20), null)) .verifyErrorSatisfies(e -> assertEquals(NullPointerException.class, e.getClass())); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createCertificateNull(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginCreateCertificate(null, null)) .verifyErrorSatisfies(e -> assertEquals(NullPointerException.class, e.getClass())); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); updateCertificateRunner((originalTags, updatedTags) -> { String certName = testResourceNamer.randomName("testCert", 20); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault(), true, originalTags); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(cert -> certificateAsyncClient .updateCertificateProperties(cert.getProperties().setTags(updatedTags)))) .assertNext(cert -> { validateMapResponse(updatedTags, cert.getProperties().getTags()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateDisabledCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); updateDisabledCertificateRunner((originalTags, updatedTags) -> { String certName = testResourceNamer.randomName("testCert", 20); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault(), false, originalTags); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(cert -> certificateAsyncClient .updateCertificateProperties(cert.getProperties().setTags(updatedTags)))) .assertNext(cert -> { validateMapResponse(updatedTags, cert.getProperties().getTags()); assertFalse(cert.getProperties().isEnabled()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expectedCert -> certificateAsyncClient.getCertificate(certificateName) .map(returnedCert -> validatePolicy(expectedCert.getPolicy(), returnedCert.getPolicy()))) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateSpecificVersion(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificateSpecificVersionRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(expectedCert -> certificateAsyncClient.getCertificateVersion(certificateName, expectedCert.getProperties().getVersion()) .map(returnedCert -> validateCertificate(expectedCert, returnedCert))) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.getCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); deleteCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(ignored -> certificateAsyncClient.beginDeleteCertificate(certificateName) .last().flatMap(asyncPollResponse -> Mono.defer(() -> Mono.just(asyncPollResponse.getValue()))) )) .assertNext(expectedCert -> { assertNotNull(expectedCert.getDeletedOn()); assertNotNull(expectedCert.getRecoveryId()); assertNotNull(expectedCert.getScheduledPurgeDate()); assertEquals(certificateName, expectedCert.getName()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginDeleteCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getDeletedCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(ignored -> certificateAsyncClient.beginDeleteCertificate(certificateName) .last().flatMap(asyncPollResponse -> Mono.just(asyncPollResponse.getValue())))) .assertNext(deletedCertificate -> { assertNotNull(deletedCertificate.getDeletedOn()); assertNotNull(deletedCertificate.getRecoveryId()); assertNotNull(deletedCertificate.getScheduledPurgeDate()); assertEquals(certificateName, deletedCertificate.getName()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.getDeletedCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); recoverDeletedKeyRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); AtomicReference<KeyVaultCertificateWithPolicy> createdCertificate = new AtomicReference<>(); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(keyVaultCertificateWithPolicy -> { createdCertificate.set(keyVaultCertificateWithPolicy); return certificateAsyncClient.beginDeleteCertificate(certificateName) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(asyncPollResponse -> Mono.just(asyncPollResponse.getValue())); }) .flatMap(ignored -> certificateAsyncClient.beginRecoverDeletedCertificate(certificateName) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(certAsyncResponse -> Mono.just(certAsyncResponse.getValue())))) .assertNext(recoveredCert -> { assertEquals(certificateName, recoveredCert.getName()); validateCertificate(createdCertificate.get(), recoveredCert); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void recoverDeletedCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.beginRecoverDeletedCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); backupCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(ignored -> certificateAsyncClient.backupCertificate(certificateName))) .assertNext(backupBytes -> { assertNotNull(backupBytes); assertTrue(backupBytes.length > 0); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void backupCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.backupCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); restoreCertificateRunner((certificateName) -> { CertificatePolicy initialPolicy = setupPolicy(); PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, initialPolicy); AtomicReference<KeyVaultCertificateWithPolicy> createdCertificate = new AtomicReference<>(); AtomicReference<Byte[]> backup = new AtomicReference<>(); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(keyVaultCertificateWithPolicy -> { createdCertificate.set(keyVaultCertificateWithPolicy); return certificateAsyncClient.backupCertificate(certificateName) .flatMap(backupBytes -> { Byte[] bytes = new Byte[backupBytes.length]; int i = 0; for (Byte bt : backupBytes) { bytes[i] = bt; i++; } backup.set(bytes); return Mono.just(backupBytes); }); })) .assertNext(backupBytes -> { assertNotNull(backupBytes); assertTrue(backupBytes.length > 0); }).verifyComplete(); StepVerifier.create(certificateAsyncClient.beginDeleteCertificate(certificateName) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().then(Mono.defer(() -> certificateAsyncClient.purgeDeletedCertificate(certificateName))) .then(Mono.just("complete"))) .assertNext(input -> assertEquals("complete", input)) .verifyComplete(); sleepInRecordMode(40000); StepVerifier.create(Mono.defer(() -> { byte[] backupBytes = new byte[backup.get().length]; for (int i = 0; i < backup.get().length; i++) { backupBytes[i] = backup.get()[i]; } return certificateAsyncClient.restoreCertificateBackup(backupBytes); })).assertNext(restoredCertificate -> { assertEquals(certificateName, restoredCertificate.getName()); validatePolicy(restoredCertificate.getPolicy(), createdCertificate.get().getPolicy()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificateOperationRunner((certificateName) -> { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, setupPolicy()); AtomicReference<KeyVaultCertificateWithPolicy> expectedCert = new AtomicReference<>(); StepVerifier.create( certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(keyVaultCertificateWithPolicy -> { expectedCert.set(keyVaultCertificateWithPolicy); return certificateAsyncClient.getCertificateOperation(certificateName) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult); })) .assertNext(retrievedCert -> { validateCertificate(expectedCert.get(), retrievedCert); validatePolicy(expectedCert.get().getPolicy(), retrievedCert.getPolicy()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificateOperation(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); deleteCertificateOperationRunner((certificateName) -> { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, CertificatePolicy.getDefault()); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(ignored -> certificateAsyncClient.deleteCertificateOperation(certificateName))) .assertNext(certificateOperation -> { assertEquals("completed", certificateOperation.getStatus()); }).verifyComplete(); StepVerifier.create(certificateAsyncClient.deleteCertificateOperation(certificateName)) .verifyErrorSatisfies(e -> { assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificatePolicyRunner((certificateName) -> { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, setupPolicy()); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult)) .assertNext(certificate -> { validatePolicy(setupPolicy(), certificate.getPolicy()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateCertificatePolicy(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); updateCertificatePolicyRunner((certificateName) -> { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certificateName, setupPolicy()); AtomicReference<KeyVaultCertificateWithPolicy> createdCert = new AtomicReference<>(); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult) .flatMap(keyVaultCertificateWithPolicy -> { keyVaultCertificateWithPolicy.getPolicy().setExportable(false); createdCert.set(keyVaultCertificateWithPolicy); return certificateAsyncClient.updateCertificatePolicy(certificateName, keyVaultCertificateWithPolicy.getPolicy()); })) .assertNext(certificatePolicy -> validatePolicy(createdCert.get().getPolicy(), certificatePolicy)).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void restoreCertificateFromMalformedBackup(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); byte[] keyBackupBytes = "non-existing".getBytes(); StepVerifier.create(certificateAsyncClient.restoreCertificateBackup(keyBackupBytes)) .verifyErrorSatisfies(e -> { assertResponseException(e, ResourceModifiedException.class, HttpURLConnection.HTTP_BAD_REQUEST); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); listCertificatesRunner((certificatesToList) -> { HashSet<String> certificates = new HashSet<>(certificatesToList); for (String certName : certificates) { StepVerifier.create(certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED).last()) .assertNext(response -> assertNotNull(response.getValue())) .verifyComplete(); } StepVerifier.create(certificateAsyncClient.listPropertiesOfCertificates() .map(certificate -> { certificates.remove(certificate.getName()); return Mono.empty(); }).last()) .assertNext(ignore -> { assertEquals(0, certificates.size()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listPropertiesOfCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); listPropertiesOfCertificatesRunner((certificatesToList) -> { HashSet<String> certificates = new HashSet<>(certificatesToList); for (String certName : certificates) { StepVerifier.create(certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()) .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED).last()) .assertNext(response -> assertNotNull(response.getValue())) .verifyComplete(); } StepVerifier.create(certificateAsyncClient.listPropertiesOfCertificates(false) .map(certificate -> { certificates.remove(certificate.getName()); return Mono.empty(); }).last()) .assertNext(ignore -> { assertEquals(0, certificates.size()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); createIssuerRunner((issuer) -> { StepVerifier.create(certificateAsyncClient.createIssuer(issuer)) .assertNext(createdIssuer -> { assertTrue(issuerCreatedCorrectly(issuer, createdIssuer)); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createIssuerEmptyName(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.createIssuer(new CertificateIssuer("", ""))) .verifyErrorSatisfies(e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createIssuerNullProvider(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.createIssuer(new CertificateIssuer("", null))) .verifyErrorSatisfies(e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_BAD_METHOD)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void createIssuerNull(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.createIssuer(null)) .verifyErrorSatisfies(e -> assertEquals(NullPointerException.class, e.getClass())); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); getCertificateIssuerRunner((issuer) -> { AtomicReference<CertificateIssuer> certificateIssuer = new AtomicReference<>(); StepVerifier.create(certificateAsyncClient.createIssuer(issuer) .flatMap(createdIssuer -> { certificateIssuer.set(createdIssuer); return certificateAsyncClient.getIssuer(issuer.getName()); })) .assertNext(retrievedIssuer -> { assertTrue(issuerCreatedCorrectly(certificateIssuer.get(), retrievedIssuer)); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.backupCertificate("non-existing")) .verifyErrorSatisfies(e -> { assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); deleteCertificateIssuerRunner((issuer) -> { AtomicReference<CertificateIssuer> createdIssuer = new AtomicReference<>(); StepVerifier.create(certificateAsyncClient.createIssuer(issuer) .flatMap(certificateIssuer -> { createdIssuer.set(certificateIssuer); return certificateAsyncClient.deleteIssuer(issuer.getName()); })) .assertNext(deletedIssuer -> { assertTrue(issuerCreatedCorrectly(createdIssuer.get(), deletedIssuer)); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void deleteCertificateIssuerNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.backupCertificate("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listCertificateIssuers(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); listCertificateIssuersRunner((certificateIssuers) -> { HashMap<String, CertificateIssuer> certificateIssuersToList = new HashMap<>(certificateIssuers); AtomicInteger count = new AtomicInteger(0); for (CertificateIssuer issuer : certificateIssuers.values()) { StepVerifier.create(certificateAsyncClient.createIssuer(issuer)) .assertNext(certificateIssuer -> { assertNotNull(certificateIssuer.getName()); }).verifyComplete(); } StepVerifier.create(certificateAsyncClient.listPropertiesOfIssuers() .map(issuerProperties -> { if (certificateIssuersToList.containsKey(issuerProperties.getName())) { count.incrementAndGet(); } return Mono.empty(); }).last()) .assertNext(ignore -> assertEquals(certificateIssuersToList.size(), count.get())) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void updateIssuer(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); updateIssuerRunner((issuerToCreate, issuerToUpdate) -> { StepVerifier.create(certificateAsyncClient.createIssuer(issuerToCreate) .flatMap(createdIssuer -> certificateAsyncClient.updateIssuer(issuerToUpdate))) .assertNext(updatedIssuer -> assertTrue(issuerUpdatedCorrectly(issuerToCreate, updatedIssuer))).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public void setContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); List<CertificateContact> contacts = Arrays.asList(setupContact()); StepVerifier.create(certificateAsyncClient.setContacts(contacts)) .assertNext(contact -> validateContact(setupContact(), contact)) .verifyComplete(); StepVerifier.create(certificateAsyncClient.deleteContacts().then(Mono.just("complete"))) .assertNext(input -> assertEquals("complete", input)).verifyComplete(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public void listContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); List<CertificateContact> contacts = Arrays.asList(setupContact()); StepVerifier.create(certificateAsyncClient.setContacts(contacts)) .assertNext(contact -> validateContact(setupContact(), contact)) .verifyComplete(); sleepInRecordMode(6000); StepVerifier.create(certificateAsyncClient.listContacts()) .assertNext(contact -> validateContact(setupContact(), contact)) .verifyComplete(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public void deleteContacts(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); List<CertificateContact> contacts = Arrays.asList(setupContact()); StepVerifier.create(certificateAsyncClient.setContacts(contacts)) .assertNext(contact -> validateContact(setupContact(), contact)) .verifyComplete(); StepVerifier.create(certificateAsyncClient.deleteContacts()) .assertNext(contact -> { validateContact(setupContact(), contact); }).verifyComplete(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificateOperationNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.getCertificateOperation("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void getCertificatePolicyNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.getCertificatePolicy("non-existing")) .verifyErrorSatisfies(e -> assertResponseException(e, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listCertificateVersions(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); String certName = testResourceNamer.randomName("testListCertVersion", 25); int versionsToCreate = 5; for (int i = 0; i < versionsToCreate; i++) { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last().flatMap(AsyncPollResponse::getFinalResult).then(Mono.just("complete"))).assertNext(input -> assertEquals("complete", input)).verifyComplete(); } AtomicInteger createdVersions = new AtomicInteger(); StepVerifier.create(certificateAsyncClient.listPropertiesOfCertificateVersions(certName) .map(certificateProperties -> { createdVersions.getAndIncrement(); return Mono.just("complete"); }).last()).assertNext(ignored -> assertEquals(versionsToCreate, createdVersions.get())).verifyComplete(); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void listDeletedCertificates(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); if (interceptorManager.isLiveMode()) { return; } listDeletedCertificatesRunner((certificates) -> { HashSet<String> certificatesToDelete = new HashSet<>(certificates); for (String certName : certificatesToDelete) { PollerFlux<CertificateOperation, KeyVaultCertificateWithPolicy> certPoller = certificateAsyncClient.beginCreateCertificate(certName, CertificatePolicy.getDefault()); StepVerifier.create(certPoller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED).last() .then(Mono.just("complete"))).assertNext(input -> assertEquals("complete", input)).verifyComplete(); } for (String certName : certificates) { PollerFlux<DeletedCertificate, Void> poller = certificateAsyncClient.beginDeleteCertificate(certName); StepVerifier.create(poller .takeUntil(apr -> apr.getStatus() == LongRunningOperationStatus.SUCCESSFULLY_COMPLETED) .last()).assertNext(asyncPollResponse -> assertNotNull(asyncPollResponse.getValue())).verifyComplete(); } sleepInRecordMode(4000); StepVerifier.create(certificateAsyncClient.listDeletedCertificates() .map(deletedCertificate -> { certificatesToDelete.remove(deletedCertificate.getName()); return Mono.just("complete"); }).last()) .assertNext(ignored -> { assertEquals(0, certificatesToDelete.size()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void importCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); importCertificateRunner((importCertificateOptions) -> { StepVerifier.create(certificateAsyncClient.importCertificate(importCertificateOptions)) .assertNext(importedCertificate -> { assertTrue(toHexString(importedCertificate.getProperties().getX509Thumbprint()) .equalsIgnoreCase("db1497bc2c82b365c5c7c73f611513ee117790a9")); assertEquals(importCertificateOptions.isEnabled(), importedCertificate.getProperties().isEnabled()); X509Certificate x509Certificate = null; try { x509Certificate = loadCerToX509Certificate(importedCertificate); } catch (CertificateException | IOException e) { e.printStackTrace(); fail(); } assertEquals("CN=KeyVaultTest", x509Certificate.getSubjectX500Principal().getName()); assertEquals("CN=KeyVaultTest", x509Certificate.getIssuerX500Principal().getName()); }).verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") public void mergeCertificateNotFound(HttpClient httpClient, CertificateServiceVersion serviceVersion) { createCertificateAsyncClient(httpClient, serviceVersion); StepVerifier.create(certificateAsyncClient.mergeCertificate( new MergeCertificateOptions(testResourceNamer.randomName("testCert", 20), Arrays.asList("test".getBytes())))) .verifyErrorSatisfies(e -> assertResponseException(e, HttpResponseException.class, HttpURLConnection.HTTP_NOT_FOUND)); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void importPemCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion) throws IOException { createCertificateAsyncClient(httpClient, serviceVersion); importPemCertificateRunner((importCertificateOptions) -> { StepVerifier.create(certificateAsyncClient.importCertificate(importCertificateOptions)) .assertNext(importedCertificate -> { assertEquals(importCertificateOptions.isEnabled(), importedCertificate.getProperties().isEnabled()); assertEquals(CertificateContentType.PEM, importedCertificate.getPolicy().getContentType()); }).verifyComplete(); }); } }
I believe these should use `headers.set` as add will create a list of values if they are added multiple times.
public static void changeHeaders(HttpRequest request, String xRecordingId, String mode) { HttpHeader upstreamUri = request.getHeaders().get("x-recording-upstream-base-uri"); UrlBuilder proxyUrlBuilder = UrlBuilder.parse(request.getUrl()); proxyUrlBuilder.setScheme(PROXY_URL_SCHEME); proxyUrlBuilder.setHost(PROXY_URL_HOST); proxyUrlBuilder.setPort(PROXY_URL_PORT); UrlBuilder originalUrlBuilder = UrlBuilder.parse(request.getUrl()); originalUrlBuilder.setPath(""); originalUrlBuilder.setQuery(""); try { URL originalUrl = originalUrlBuilder.toUrl(); HttpHeaders headers = request.getHeaders(); if (upstreamUri == null) { headers.add("x-recording-upstream-base-uri", originalUrl.toString()); headers.add("x-recording-mode", mode); headers.add("x-recording-id", xRecordingId); } request.setUrl(proxyUrlBuilder.toUrl()); } catch (MalformedURLException e) { throw new RuntimeException(e); } }
headers.add("x-recording-id", xRecordingId);
public static void changeHeaders(HttpRequest request, String xRecordingId, String mode) { HttpHeader upstreamUri = request.getHeaders().get("x-recording-upstream-base-uri"); UrlBuilder proxyUrlBuilder = UrlBuilder.parse(request.getUrl()); proxyUrlBuilder.setScheme(PROXY_URL_SCHEME); proxyUrlBuilder.setHost(PROXY_URL_HOST); proxyUrlBuilder.setPort(PROXY_URL_PORT); UrlBuilder originalUrlBuilder = UrlBuilder.parse(request.getUrl()); originalUrlBuilder.setPath(""); originalUrlBuilder.setQuery(""); try { URL originalUrl = originalUrlBuilder.toUrl(); HttpHeaders headers = request.getHeaders(); if (upstreamUri == null) { headers.set("x-recording-upstream-base-uri", originalUrl.toString()); headers.set("x-recording-mode", mode); headers.set("x-recording-id", xRecordingId); } request.setUrl(proxyUrlBuilder.toUrl()); } catch (MalformedURLException e) { throw new RuntimeException(e); } }
class TestProxyUtils { private static final ClientLogger LOGGER = new ClientLogger(TestProxyUtils.class); private static final String PROXY_URL_SCHEME = "http"; private static final String PROXY_URL_HOST = "localhost"; private static final int PROXY_URL_PORT = 5000; private static final String PROXY_URL = String.format("%s: private static final List<String> JSON_PROPERTIES_TO_REDACT = new ArrayList<String>( Arrays.asList("authHeader", "accountKey", "accessToken", "accountName", "applicationId", "apiKey", "connectionString", "url", "host", "password", "userName")); private static final Map<String, String> HEADER_KEY_REGEX_TO_REDACT = new HashMap<String, String>() {{ put("Operation-Location", URL_REGEX); put("operation-location", URL_REGEX); }}; private static final List<String> BODY_REGEX_TO_REDACT = new ArrayList<>(Arrays.asList("(?:<Value>)(?<secret>.*)(?:</Value>)", "(?:Password=)(?<secret>.*)(?:;)", "(?:User ID=)(?<secret>.*)(?:;)", "(?:<PrimaryKey>)(?<secret>.*)(?:</PrimaryKey>)", "(?:<SecondaryKey>)(?<secret>.*)(?:</SecondaryKey>)")); private static final String URL_REGEX = "(?<=http: private static final List<String> HEADER_KEYS_TO_REDACT = new ArrayList<>(Arrays.asList("Ocp-Apim-Subscription-Key", "api-key")); private static final String REDACTED_VALUE = "REDACTED"; private static final String DELEGATION_KEY_CLIENTID_REGEX = "(?:<SignedOid>)(?<secret>.*)(?:</SignedOid>)"; private static final String DELEGATION_KEY_TENANTID_REGEX = "(?:<SignedTid>)(?<secret>.*)(?:</SignedTid>)"; /** * Get the proxy URL. * * @return A string containing the proxy URL. */ public static String getProxyUrl() { return PROXY_URL; } /** * Adds headers required for communication with the test proxy. * * @param request The request to add headers to. * @param xRecordingId The x-recording-id value for the current session. * @param mode The current test proxy mode. * @throws RuntimeException Construction of one of the URLs failed. */ /** * Sets the response URL back to the original URL before returning it through the pipeline. * @param response The {@link HttpResponse} to modify. * @return The modified response. * @throws RuntimeException Construction of one of the URLs failed. */ public static HttpResponse revertUrl(HttpResponse response) { try { URL originalUrl = UrlBuilder.parse(response.getRequest().getHeaders().getValue("x-recording-upstream-base-uri")).toUrl(); UrlBuilder currentUrl = UrlBuilder.parse(response.getRequest().getUrl()); currentUrl.setScheme(originalUrl.getProtocol()); currentUrl.setHost(originalUrl.getHost()); int port = originalUrl.getPort(); if (port == -1) { currentUrl.setPort(""); } else { currentUrl.setPort(port); } response.getRequest().setUrl(currentUrl.toUrl()); return response; } catch (MalformedURLException e) { throw new RuntimeException(e); } } /** * Gets the process name of the test proxy binary. * @return The platform specific process name. * @throws UnsupportedOperationException The current OS is not recognized. */ public static String getProxyProcessName() { String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (osName.contains("windows")) { return "test-proxy.exe"; } else if (osName.contains("linux")) { return "test-proxy"; } else if (osName.contains("mac os x")) { return "test-proxy"; } else { throw new UnsupportedOperationException(); } } /** * Checks the return from a request through the test proxy for special error headers. * @param httpResponse The {@link HttpResponse} from the test proxy. */ public static void checkForTestProxyErrors(HttpResponse httpResponse) { String error = httpResponse.getHeaderValue("x-request-mismatch-error"); if (error == null) { error = httpResponse.getHeaderValue("x-request-known-exception-error"); } if (error == null) { error = httpResponse.getHeaderValue("x-request-exception-exception-error"); } if (error != null) { throw LOGGER.logExceptionAsError(new RuntimeException("Test proxy exception: " + new String(Base64.getDecoder().decode(error), StandardCharsets.UTF_8))); } } /** * Registers the default set of sanitizers for sanitizing request and responses * @return the list of default sanitizers to be added. */ public static List<TestProxySanitizer> loadSanitizers() { List<TestProxySanitizer> sanitizers = new ArrayList<>(addDefaultRegexSanitizers()); sanitizers.add(addDefaultUrlSanitizer()); sanitizers.addAll(addDefaultBodySanitizers()); sanitizers.addAll(addDefaultHeaderKeySanitizers()); return sanitizers; } private static String createCustomMatcherRequestBody(CustomMatcher customMatcher) { return String.format("{\"ignoredHeaders\":\"%s\",\"excludedHeaders\":\"%s\",\"compareBodies\":%s,\"ignoredQueryParameters\":\"%s\", \"ignoreQueryOrdering\":%s}", getCommaSeperatedString(customMatcher.getHeadersKeyOnlyMatch()), getCommaSeperatedString(customMatcher.getExcludedHeaders()), customMatcher.isComparingBodies(), getCommaSeperatedString(customMatcher.getIgnoredQueryParameters()), customMatcher.isQueryOrderingIgnored()); } private static String getCommaSeperatedString(List<String> stringList) { if (stringList == null) { return null; } return stringList.stream() .filter(s -> s != null && !s.isEmpty()) .collect(Collectors.joining(",")); } private static String createBodyJsonKeyRequestBody(String jsonKey, String regex, String redactedValue) { if (regex == null) { return String.format("{\"value\":\"%s\",\"jsonPath\":\"%s\"}", redactedValue, jsonKey); } else { return String.format("{\"value\":\"%s\",\"jsonPath\":\"%s\",\"regex\":\"%s\"}", redactedValue, jsonKey, regex); } } private static String createRegexRequestBody(String key, String regex, String value, String groupForReplace) { if (key == null) { if (groupForReplace == null) { return String.format("{\"value\":\"%s\",\"regex\":\"%s\"}", value, regex); } else { return String.format("{\"value\":\"%s\",\"regex\":\"%s\",\"groupForReplace\":\"%s\"}", value, regex, groupForReplace); } } else if (regex == null) { return String.format("{\"key\":\"%s\",\"value\":\"%s\"}", key, value); } if (groupForReplace == null) { return String.format("{\"key\":\"%s\",\"value\":\"%s\",\"regex\":\"%s\"}", key, value, regex); } else { return String.format("{\"key\":\"%s\",\"value\":\"%s\",\"regex\":\"%s\",\"groupForReplace\":\"%s\"}", key, value, regex, groupForReplace); } } /** * Creates a list of sanitizer requests to be sent to the test proxy server. * * @param sanitizers the list of sanitizers to be added * @return the list of sanitizer {@link HttpRequest requests} to be sent. * @throws RuntimeException if {@link TestProxySanitizerType} is not supported. */ public static List<HttpRequest> getSanitizerRequests(List<TestProxySanitizer> sanitizers) { return sanitizers.stream().map(testProxySanitizer -> { String requestBody; String sanitizerType; switch (testProxySanitizer.getType()) { case URL: sanitizerType = TestProxySanitizerType.URL.getName(); requestBody = createRegexRequestBody(null, testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); return createHttpRequest(requestBody, sanitizerType); case BODY_REGEX: sanitizerType = TestProxySanitizerType.BODY_REGEX.getName(); requestBody = createRegexRequestBody(null, testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); return createHttpRequest(requestBody, sanitizerType); case BODY_KEY: sanitizerType = TestProxySanitizerType.BODY_KEY.getName(); requestBody = createBodyJsonKeyRequestBody(testProxySanitizer.getKey(), testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue()); return createHttpRequest(requestBody, sanitizerType); case HEADER: sanitizerType = HEADER.getName(); if (testProxySanitizer.getKey() == null && testProxySanitizer.getRegex() == null) { throw new RuntimeException( String.format("Missing regexKey and/or headerKey for sanitizer type {%s}", sanitizerType)); } requestBody = createRegexRequestBody(testProxySanitizer.getKey(), testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); return createHttpRequest(requestBody, sanitizerType); default: throw new RuntimeException( String.format("Sanitizer type {%s} not supported", testProxySanitizer.getType())); } }).collect(Collectors.toList()); } private static HttpRequest createHttpRequest(String requestBody, String sanitizerType) { HttpRequest request = new HttpRequest(HttpMethod.POST, String.format("%s/Admin/AddSanitizer", TestProxyUtils.getProxyUrl())) .setBody(requestBody); request.setHeader("x-abstraction-identifier", sanitizerType); return request; } /** * Creates a {@link List} of {@link HttpRequest} to be sent to the test proxy to register matchers. * @param matchers The {@link TestProxyRequestMatcher}s to encode into requests. * @return The {@link HttpRequest}s to send to the proxy. * @throws RuntimeException The {@link TestProxyRequestMatcher.TestProxyRequestMatcherType} is unsupported. */ public static List<HttpRequest> getMatcherRequests(List<TestProxyRequestMatcher> matchers) { return matchers.stream().map(testProxyMatcher -> { HttpRequest request; String matcherType; switch (testProxyMatcher.getType()) { case HEADERLESS: matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.HEADERLESS.getName(); request = new HttpRequest(HttpMethod.POST, String.format("%s/Admin/setmatcher", TestProxyUtils.getProxyUrl())); break; case BODILESS: request = new HttpRequest(HttpMethod.POST, String.format("%s/Admin/setmatcher", TestProxyUtils.getProxyUrl())); matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.BODILESS.getName(); break; case CUSTOM: CustomMatcher customMatcher = (CustomMatcher) testProxyMatcher; String requestBody = createCustomMatcherRequestBody(customMatcher); matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.CUSTOM.getName(); request = new HttpRequest(HttpMethod.POST, String.format("%s/Admin/setmatcher", TestProxyUtils.getProxyUrl())).setBody(requestBody); break; default: throw new RuntimeException(String.format("Matcher type {%s} not supported", testProxyMatcher.getType())); } request.setHeader("x-abstraction-identifier", matcherType); return request; }).collect(Collectors.toList()); } private static TestProxySanitizer addDefaultUrlSanitizer() { return new TestProxySanitizer(URL_REGEX, REDACTED_VALUE, TestProxySanitizerType.URL); } private static List<TestProxySanitizer> addDefaultBodySanitizers() { return JSON_PROPERTIES_TO_REDACT.stream() .map(jsonProperty -> new TestProxySanitizer(String.format("$..%s", jsonProperty), null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY)) .collect(Collectors.toList()); } private static List<TestProxySanitizer> addDefaultRegexSanitizers() { List<TestProxySanitizer> regexSanitizers = getUserDelegationSanitizers(); regexSanitizers.addAll(BODY_REGEX_TO_REDACT.stream() .map(bodyRegex -> new TestProxySanitizer(bodyRegex, REDACTED_VALUE, TestProxySanitizerType.BODY_REGEX).setGroupForReplace("secret")) .collect(Collectors.toList())); List<TestProxySanitizer> keyRegexSanitizers = new ArrayList<>(); HEADER_KEY_REGEX_TO_REDACT.forEach((key, regex) -> keyRegexSanitizers.add(new TestProxySanitizer(key, regex, REDACTED_VALUE, HEADER))); regexSanitizers.addAll(keyRegexSanitizers); return regexSanitizers; } private static List<TestProxySanitizer> addDefaultHeaderKeySanitizers() { return HEADER_KEYS_TO_REDACT.stream() .map(headerKey -> new TestProxySanitizer(headerKey, null, REDACTED_VALUE, HEADER)) .collect(Collectors.toList()); } private static List<TestProxySanitizer> getUserDelegationSanitizers() { List<TestProxySanitizer> userDelegationSanitizers = new ArrayList<>(); userDelegationSanitizers.add(new TestProxySanitizer(DELEGATION_KEY_CLIENTID_REGEX, REDACTED_VALUE, TestProxySanitizerType.BODY_REGEX).setGroupForReplace("secret")); userDelegationSanitizers.add(new TestProxySanitizer(DELEGATION_KEY_TENANTID_REGEX, REDACTED_VALUE, TestProxySanitizerType.BODY_REGEX).setGroupForReplace("secret")); return userDelegationSanitizers; } }
class TestProxyUtils { private static final ClientLogger LOGGER = new ClientLogger(TestProxyUtils.class); private static final String PROXY_URL_SCHEME = "http"; private static final String PROXY_URL_HOST = "localhost"; private static final int PROXY_URL_PORT = 5000; private static final String PROXY_URL = String.format("%s: private static final List<String> JSON_PROPERTIES_TO_REDACT = new ArrayList<String>( Arrays.asList("authHeader", "accountKey", "accessToken", "accountName", "applicationId", "apiKey", "connectionString", "url", "host", "password", "userName")); private static final Map<String, String> HEADER_KEY_REGEX_TO_REDACT = new HashMap<String, String>() {{ put("Operation-Location", URL_REGEX); put("operation-location", URL_REGEX); }}; private static final List<String> BODY_REGEX_TO_REDACT = new ArrayList<>(Arrays.asList("(?:<Value>)(?<secret>.*)(?:</Value>)", "(?:Password=)(?<secret>.*)(?:;)", "(?:User ID=)(?<secret>.*)(?:;)", "(?:<PrimaryKey>)(?<secret>.*)(?:</PrimaryKey>)", "(?:<SecondaryKey>)(?<secret>.*)(?:</SecondaryKey>)")); private static final String URL_REGEX = "(?<=http: private static final List<String> HEADER_KEYS_TO_REDACT = new ArrayList<>(Arrays.asList("Ocp-Apim-Subscription-Key", "api-key")); private static final String REDACTED_VALUE = "REDACTED"; private static final String DELEGATION_KEY_CLIENTID_REGEX = "(?:<SignedOid>)(?<secret>.*)(?:</SignedOid>)"; private static final String DELEGATION_KEY_TENANTID_REGEX = "(?:<SignedTid>)(?<secret>.*)(?:</SignedTid>)"; /** * Get the proxy URL. * * @return A string containing the proxy URL. */ public static String getProxyUrl() { return PROXY_URL; } /** * Adds headers required for communication with the test proxy. * * @param request The request to add headers to. * @param xRecordingId The x-recording-id value for the current session. * @param mode The current test proxy mode. * @throws RuntimeException Construction of one of the URLs failed. */ /** * Sets the response URL back to the original URL before returning it through the pipeline. * @param response The {@link HttpResponse} to modify. * @return The modified response. * @throws RuntimeException Construction of one of the URLs failed. */ public static HttpResponse revertUrl(HttpResponse response) { try { URL originalUrl = UrlBuilder.parse(response.getRequest().getHeaders().getValue("x-recording-upstream-base-uri")).toUrl(); UrlBuilder currentUrl = UrlBuilder.parse(response.getRequest().getUrl()); currentUrl.setScheme(originalUrl.getProtocol()); currentUrl.setHost(originalUrl.getHost()); int port = originalUrl.getPort(); if (port == -1) { currentUrl.setPort(""); } else { currentUrl.setPort(port); } response.getRequest().setUrl(currentUrl.toUrl()); return response; } catch (MalformedURLException e) { throw new RuntimeException(e); } } /** * Gets the process name of the test proxy binary. * @return The platform specific process name. * @throws UnsupportedOperationException The current OS is not recognized. */ public static String getProxyProcessName() { String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (osName.contains("windows")) { return "test-proxy.exe"; } else if (osName.contains("linux")) { return "test-proxy"; } else if (osName.contains("mac os x")) { return "test-proxy"; } else { throw new UnsupportedOperationException(); } } /** * Checks the return from a request through the test proxy for special error headers. * @param httpResponse The {@link HttpResponse} from the test proxy. */ public static void checkForTestProxyErrors(HttpResponse httpResponse) { String error = httpResponse.getHeaderValue("x-request-mismatch-error"); if (error == null) { error = httpResponse.getHeaderValue("x-request-known-exception-error"); } if (error == null) { error = httpResponse.getHeaderValue("x-request-exception-exception-error"); } if (error != null) { throw LOGGER.logExceptionAsError(new RuntimeException("Test proxy exception: " + new String(Base64.getDecoder().decode(error), StandardCharsets.UTF_8))); } } /** * Registers the default set of sanitizers for sanitizing request and responses * @return the list of default sanitizers to be added. */ public static List<TestProxySanitizer> loadSanitizers() { List<TestProxySanitizer> sanitizers = new ArrayList<>(addDefaultRegexSanitizers()); sanitizers.add(addDefaultUrlSanitizer()); sanitizers.addAll(addDefaultBodySanitizers()); sanitizers.addAll(addDefaultHeaderKeySanitizers()); return sanitizers; } private static String createCustomMatcherRequestBody(CustomMatcher customMatcher) { return String.format("{\"ignoredHeaders\":\"%s\",\"excludedHeaders\":\"%s\",\"compareBodies\":%s,\"ignoredQueryParameters\":\"%s\", \"ignoreQueryOrdering\":%s}", getCommaSeperatedString(customMatcher.getHeadersKeyOnlyMatch()), getCommaSeperatedString(customMatcher.getExcludedHeaders()), customMatcher.isComparingBodies(), getCommaSeperatedString(customMatcher.getIgnoredQueryParameters()), customMatcher.isQueryOrderingIgnored()); } private static String getCommaSeperatedString(List<String> stringList) { if (stringList == null) { return null; } return stringList.stream() .filter(s -> s != null && !s.isEmpty()) .collect(Collectors.joining(",")); } private static String createBodyJsonKeyRequestBody(String jsonKey, String regex, String redactedValue) { if (regex == null) { return String.format("{\"value\":\"%s\",\"jsonPath\":\"%s\"}", redactedValue, jsonKey); } else { return String.format("{\"value\":\"%s\",\"jsonPath\":\"%s\",\"regex\":\"%s\"}", redactedValue, jsonKey, regex); } } private static String createRegexRequestBody(String key, String regex, String value, String groupForReplace) { if (key == null) { if (groupForReplace == null) { return String.format("{\"value\":\"%s\",\"regex\":\"%s\"}", value, regex); } else { return String.format("{\"value\":\"%s\",\"regex\":\"%s\",\"groupForReplace\":\"%s\"}", value, regex, groupForReplace); } } else if (regex == null) { return String.format("{\"key\":\"%s\",\"value\":\"%s\"}", key, value); } if (groupForReplace == null) { return String.format("{\"key\":\"%s\",\"value\":\"%s\",\"regex\":\"%s\"}", key, value, regex); } else { return String.format("{\"key\":\"%s\",\"value\":\"%s\",\"regex\":\"%s\",\"groupForReplace\":\"%s\"}", key, value, regex, groupForReplace); } } /** * Creates a list of sanitizer requests to be sent to the test proxy server. * * @param sanitizers the list of sanitizers to be added * @return the list of sanitizer {@link HttpRequest requests} to be sent. * @throws RuntimeException if {@link TestProxySanitizerType} is not supported. */ public static List<HttpRequest> getSanitizerRequests(List<TestProxySanitizer> sanitizers) { return sanitizers.stream().map(testProxySanitizer -> { String requestBody; String sanitizerType; switch (testProxySanitizer.getType()) { case URL: sanitizerType = TestProxySanitizerType.URL.getName(); requestBody = createRegexRequestBody(null, testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); return createHttpRequest(requestBody, sanitizerType); case BODY_REGEX: sanitizerType = TestProxySanitizerType.BODY_REGEX.getName(); requestBody = createRegexRequestBody(null, testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); return createHttpRequest(requestBody, sanitizerType); case BODY_KEY: sanitizerType = TestProxySanitizerType.BODY_KEY.getName(); requestBody = createBodyJsonKeyRequestBody(testProxySanitizer.getKey(), testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue()); return createHttpRequest(requestBody, sanitizerType); case HEADER: sanitizerType = HEADER.getName(); if (testProxySanitizer.getKey() == null && testProxySanitizer.getRegex() == null) { throw new RuntimeException( String.format("Missing regexKey and/or headerKey for sanitizer type {%s}", sanitizerType)); } requestBody = createRegexRequestBody(testProxySanitizer.getKey(), testProxySanitizer.getRegex(), testProxySanitizer.getRedactedValue(), testProxySanitizer.getGroupForReplace()); return createHttpRequest(requestBody, sanitizerType); default: throw new RuntimeException( String.format("Sanitizer type {%s} not supported", testProxySanitizer.getType())); } }).collect(Collectors.toList()); } private static HttpRequest createHttpRequest(String requestBody, String sanitizerType) { HttpRequest request = new HttpRequest(HttpMethod.POST, String.format("%s/Admin/AddSanitizer", TestProxyUtils.getProxyUrl())) .setBody(requestBody); request.setHeader("x-abstraction-identifier", sanitizerType); return request; } /** * Creates a {@link List} of {@link HttpRequest} to be sent to the test proxy to register matchers. * @param matchers The {@link TestProxyRequestMatcher}s to encode into requests. * @return The {@link HttpRequest}s to send to the proxy. * @throws RuntimeException The {@link TestProxyRequestMatcher.TestProxyRequestMatcherType} is unsupported. */ public static List<HttpRequest> getMatcherRequests(List<TestProxyRequestMatcher> matchers) { return matchers.stream().map(testProxyMatcher -> { HttpRequest request; String matcherType; switch (testProxyMatcher.getType()) { case HEADERLESS: matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.HEADERLESS.getName(); request = new HttpRequest(HttpMethod.POST, String.format("%s/Admin/setmatcher", TestProxyUtils.getProxyUrl())); break; case BODILESS: request = new HttpRequest(HttpMethod.POST, String.format("%s/Admin/setmatcher", TestProxyUtils.getProxyUrl())); matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.BODILESS.getName(); break; case CUSTOM: CustomMatcher customMatcher = (CustomMatcher) testProxyMatcher; String requestBody = createCustomMatcherRequestBody(customMatcher); matcherType = TestProxyRequestMatcher.TestProxyRequestMatcherType.CUSTOM.getName(); request = new HttpRequest(HttpMethod.POST, String.format("%s/Admin/setmatcher", TestProxyUtils.getProxyUrl())).setBody(requestBody); break; default: throw new RuntimeException(String.format("Matcher type {%s} not supported", testProxyMatcher.getType())); } request.setHeader("x-abstraction-identifier", matcherType); return request; }).collect(Collectors.toList()); } private static TestProxySanitizer addDefaultUrlSanitizer() { return new TestProxySanitizer(URL_REGEX, REDACTED_VALUE, TestProxySanitizerType.URL); } private static List<TestProxySanitizer> addDefaultBodySanitizers() { return JSON_PROPERTIES_TO_REDACT.stream() .map(jsonProperty -> new TestProxySanitizer(String.format("$..%s", jsonProperty), null, REDACTED_VALUE, TestProxySanitizerType.BODY_KEY)) .collect(Collectors.toList()); } private static List<TestProxySanitizer> addDefaultRegexSanitizers() { List<TestProxySanitizer> regexSanitizers = getUserDelegationSanitizers(); regexSanitizers.addAll(BODY_REGEX_TO_REDACT.stream() .map(bodyRegex -> new TestProxySanitizer(bodyRegex, REDACTED_VALUE, TestProxySanitizerType.BODY_REGEX).setGroupForReplace("secret")) .collect(Collectors.toList())); List<TestProxySanitizer> keyRegexSanitizers = new ArrayList<>(); HEADER_KEY_REGEX_TO_REDACT.forEach((key, regex) -> keyRegexSanitizers.add(new TestProxySanitizer(key, regex, REDACTED_VALUE, HEADER))); regexSanitizers.addAll(keyRegexSanitizers); return regexSanitizers; } private static List<TestProxySanitizer> addDefaultHeaderKeySanitizers() { return HEADER_KEYS_TO_REDACT.stream() .map(headerKey -> new TestProxySanitizer(headerKey, null, REDACTED_VALUE, HEADER)) .collect(Collectors.toList()); } private static List<TestProxySanitizer> getUserDelegationSanitizers() { List<TestProxySanitizer> userDelegationSanitizers = new ArrayList<>(); userDelegationSanitizers.add(new TestProxySanitizer(DELEGATION_KEY_CLIENTID_REGEX, REDACTED_VALUE, TestProxySanitizerType.BODY_REGEX).setGroupForReplace("secret")); userDelegationSanitizers.add(new TestProxySanitizer(DELEGATION_KEY_TENANTID_REGEX, REDACTED_VALUE, TestProxySanitizerType.BODY_REGEX).setGroupForReplace("secret")); return userDelegationSanitizers; } }
for consistency with below, parameter name should be should be `processTimeout` or `processTimeoutDuration`
public DefaultAzureCredentialBuilder processTimeout(Duration duration) { this.identityClientOptions.setProcessTimeout(duration); return this; }
this.identityClientOptions.setProcessTimeout(duration);
public DefaultAzureCredentialBuilder processTimeout(Duration duration) { this.identityClientOptions.setProcessTimeout(duration); return this; }
class DefaultAzureCredentialBuilder extends CredentialBuilderBase<DefaultAzureCredentialBuilder> { private static final ClientLogger LOGGER = new ClientLogger(DefaultAzureCredentialBuilder.class); private String tenantId; private String managedIdentityClientId; private String workloadIdentityClientId; private String managedIdentityResourceId; private List<String> additionallyAllowedTenants = IdentityUtil .getAdditionalTenantsFromEnvironment(Configuration.getGlobalConfiguration().clone()); /** * Creates an instance of a DefaultAzureCredentialBuilder. */ public DefaultAzureCredentialBuilder() { this.identityClientOptions.setIdentityLogOptionsImpl(new IdentityLogOptionsImpl(true)); } /** * Sets the tenant id of the user to authenticate through the {@link DefaultAzureCredential}. If unset, the value * in the AZURE_TENANT_ID environment variable will be used. If neither is set, the default is null * and will authenticate users to their default tenant. * * @param tenantId the tenant ID to set. * @return An updated instance of this builder with the tenant id set as specified. */ public DefaultAzureCredentialBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return An updated instance of this builder with the authority host set as specified. */ public DefaultAzureCredentialBuilder authorityHost(String authorityHost) { this.identityClientOptions.setAuthorityHost(authorityHost); return this; } /** * Specifies the KeePass database path to read the cached credentials of Azure toolkit for IntelliJ plugin. * The {@code databasePath} is required on Windows platform. For macOS and Linux platform native key chain / * key ring will be accessed respectively to retrieve the cached credentials. * * <p>This path can be located in the IntelliJ IDE. * Windows: File -&gt; Settings -&gt; Appearance &amp; Behavior -&gt; System Settings -&gt; Passwords. </p> * * @param databasePath the path to the KeePass database. * @throws IllegalArgumentException if {@code databasePath} is either not specified or is empty. * @return An updated instance of this builder with the KeePass database path set as specified. */ public DefaultAzureCredentialBuilder intelliJKeePassDatabasePath(String databasePath) { if (CoreUtils.isNullOrEmpty(databasePath)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The KeePass database path is either empty or not configured." + " Please configure it on the builder.")); } this.identityClientOptions.setIntelliJKeePassDatabasePath(databasePath); return this; } /** * Specifies the client ID of user assigned or system assigned identity, when this credential is running * in an environment with managed identities. If unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If neither is set, the default value is null and will only work with system assigned * managed identities and not user assigned managed identities. * * Only one of managedIdentityClientId and managedIdentityResourceId can be specified. * * @param clientId the client ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder managedIdentityClientId(String clientId) { this.managedIdentityClientId = clientId; return this; } /** * Specifies the client ID of Azure AD app to be used for AKS workload identity authentication. * if unset, {@link DefaultAzureCredentialBuilder * If both values are unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If none are set, the default value is null and Workload Identity authentication will not be attempted. * * @param clientId the client ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder workloadIdentityClientId(String clientId) { this.workloadIdentityClientId = clientId; return this; } /** * Specifies the resource ID of user assigned or system assigned identity, when this credential is running * in an environment with managed identities. If unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If neither is set, the default value is null and will only work with system assigned * managed identities and not user assigned managed identities. * * Only one of managedIdentityResourceId and managedIdentityClientId can be specified. * * @param resourceId the resource ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder managedIdentityResourceId(String resourceId) { this.managedIdentityResourceId = resourceId; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return An updated instance of this builder with the executor service set as specified. */ public DefaultAzureCredentialBuilder executorService(ExecutorService executorService) { this.identityClientOptions.setExecutorService(executorService); return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public DefaultAzureCredentialBuilder additionallyAllowedTenants(String... additionallyAllowedTenants) { this.additionallyAllowedTenants = IdentityUtil.resolveAdditionalTenants(Arrays.asList(additionallyAllowedTenants)); return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public DefaultAzureCredentialBuilder additionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = IdentityUtil.resolveAdditionalTenants(additionallyAllowedTenants); return this; } /** * Specifies a {@link Duration} timeout for developer credentials (such as Azure CLI) that rely on separate process * invocations. * @param duration The {@link Duration} to wait. * @return An updated instance of this builder with the timeout specified. */ /** * Disable instance discovery. Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return An updated instance of this builder with instance discovery disabled. */ public DefaultAzureCredentialBuilder disableInstanceDiscovery() { this.identityClientOptions.disableInstanceDisovery(); return this; } /** * Creates new {@link DefaultAzureCredential} with the configured options set. * * @return a {@link DefaultAzureCredential} with the current configurations. * @throws IllegalStateException if clientId and resourceId are both set. */ public DefaultAzureCredential build() { loadFallbackValuesFromEnvironment(); if (managedIdentityClientId != null && managedIdentityResourceId != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Only one of managedIdentityResourceId and managedIdentityClientId can be specified.")); } if (!CoreUtils.isNullOrEmpty(additionallyAllowedTenants)) { identityClientOptions.setAdditionallyAllowedTenants(additionallyAllowedTenants); } return new DefaultAzureCredential(getCredentialsChain()); } private void loadFallbackValuesFromEnvironment() { Configuration configuration = identityClientOptions.getConfiguration() == null ? Configuration.getGlobalConfiguration().clone() : identityClientOptions.getConfiguration(); tenantId = CoreUtils.isNullOrEmpty(tenantId) ? configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID) : tenantId; managedIdentityClientId = CoreUtils.isNullOrEmpty(managedIdentityClientId) ? configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID) : managedIdentityClientId; } private ArrayList<TokenCredential> getCredentialsChain() { WorkloadIdentityCredential workloadIdentityCredential = getWorkloadIdentityCredentialIfAvailable(); ArrayList<TokenCredential> output = new ArrayList<TokenCredential>(workloadIdentityCredential != null ? 8 : 7); output.add(new EnvironmentCredential(identityClientOptions.clone())); if (workloadIdentityCredential != null) { output.add(workloadIdentityCredential); } output.add(new ManagedIdentityCredential(managedIdentityClientId, managedIdentityResourceId, identityClientOptions.clone())); output.add(new AzureDeveloperCliCredential(tenantId, identityClientOptions.clone())); output.add(new SharedTokenCacheCredential(null, IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID, tenantId, identityClientOptions.clone())); output.add(new IntelliJCredential(tenantId, identityClientOptions.clone())); output.add(new AzureCliCredential(tenantId, identityClientOptions.clone())); output.add(new AzurePowerShellCredential(tenantId, identityClientOptions.clone())); return output; } private WorkloadIdentityCredential getWorkloadIdentityCredentialIfAvailable() { Configuration configuration = identityClientOptions.getConfiguration() == null ? Configuration.getGlobalConfiguration().clone() : identityClientOptions.getConfiguration(); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String federatedTokenFilePath = configuration.get(AZURE_FEDERATED_TOKEN_FILE); String azureAuthorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST); String clientId = CoreUtils.isNullOrEmpty(workloadIdentityClientId) ? managedIdentityClientId : workloadIdentityClientId; if (!(CoreUtils.isNullOrEmpty(tenantId) || CoreUtils.isNullOrEmpty(federatedTokenFilePath) || CoreUtils.isNullOrEmpty(clientId) || CoreUtils.isNullOrEmpty(azureAuthorityHost))) { return new WorkloadIdentityCredential(tenantId, clientId, federatedTokenFilePath, identityClientOptions.setAuthorityHost(azureAuthorityHost).clone()); } return null; } }
class DefaultAzureCredentialBuilder extends CredentialBuilderBase<DefaultAzureCredentialBuilder> { private static final ClientLogger LOGGER = new ClientLogger(DefaultAzureCredentialBuilder.class); private String tenantId; private String managedIdentityClientId; private String workloadIdentityClientId; private String managedIdentityResourceId; private List<String> additionallyAllowedTenants = IdentityUtil .getAdditionalTenantsFromEnvironment(Configuration.getGlobalConfiguration().clone()); /** * Creates an instance of a DefaultAzureCredentialBuilder. */ public DefaultAzureCredentialBuilder() { this.identityClientOptions.setIdentityLogOptionsImpl(new IdentityLogOptionsImpl(true)); } /** * Sets the tenant id of the user to authenticate through the {@link DefaultAzureCredential}. If unset, the value * in the AZURE_TENANT_ID environment variable will be used. If neither is set, the default is null * and will authenticate users to their default tenant. * * @param tenantId the tenant ID to set. * @return An updated instance of this builder with the tenant id set as specified. */ public DefaultAzureCredentialBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } /** * Specifies the Azure Active Directory endpoint to acquire tokens. * @param authorityHost the Azure Active Directory endpoint * @return An updated instance of this builder with the authority host set as specified. */ public DefaultAzureCredentialBuilder authorityHost(String authorityHost) { this.identityClientOptions.setAuthorityHost(authorityHost); return this; } /** * Specifies the KeePass database path to read the cached credentials of Azure toolkit for IntelliJ plugin. * The {@code databasePath} is required on Windows platform. For macOS and Linux platform native key chain / * key ring will be accessed respectively to retrieve the cached credentials. * * <p>This path can be located in the IntelliJ IDE. * Windows: File -&gt; Settings -&gt; Appearance &amp; Behavior -&gt; System Settings -&gt; Passwords. </p> * * @param databasePath the path to the KeePass database. * @throws IllegalArgumentException if {@code databasePath} is either not specified or is empty. * @return An updated instance of this builder with the KeePass database path set as specified. */ public DefaultAzureCredentialBuilder intelliJKeePassDatabasePath(String databasePath) { if (CoreUtils.isNullOrEmpty(databasePath)) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("The KeePass database path is either empty or not configured." + " Please configure it on the builder.")); } this.identityClientOptions.setIntelliJKeePassDatabasePath(databasePath); return this; } /** * Specifies the client ID of user assigned or system assigned identity, when this credential is running * in an environment with managed identities. If unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If neither is set, the default value is null and will only work with system assigned * managed identities and not user assigned managed identities. * * Only one of managedIdentityClientId and managedIdentityResourceId can be specified. * * @param clientId the client ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder managedIdentityClientId(String clientId) { this.managedIdentityClientId = clientId; return this; } /** * Specifies the client ID of Azure AD app to be used for AKS workload identity authentication. * if unset, {@link DefaultAzureCredentialBuilder * If both values are unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If none are set, the default value is null and Workload Identity authentication will not be attempted. * * @param clientId the client ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder workloadIdentityClientId(String clientId) { this.workloadIdentityClientId = clientId; return this; } /** * Specifies the resource ID of user assigned or system assigned identity, when this credential is running * in an environment with managed identities. If unset, the value in the AZURE_CLIENT_ID environment variable * will be used. If neither is set, the default value is null and will only work with system assigned * managed identities and not user assigned managed identities. * * Only one of managedIdentityResourceId and managedIdentityClientId can be specified. * * @param resourceId the resource ID * @return the DefaultAzureCredentialBuilder itself */ public DefaultAzureCredentialBuilder managedIdentityResourceId(String resourceId) { this.managedIdentityResourceId = resourceId; return this; } /** * Specifies the ExecutorService to be used to execute the authentication requests. * Developer is responsible for maintaining the lifecycle of the ExecutorService. * * <p> * If this is not configured, the {@link ForkJoinPool * also shared with other application tasks. If the common pool is heavily used for other tasks, authentication * requests might starve and setting up this executor service should be considered. * </p> * * <p> The executor service and can be safely shutdown if the TokenCredential is no longer being used by the * Azure SDK clients and should be shutdown before the application exits. </p> * * @param executorService the executor service to use for executing authentication requests. * @return An updated instance of this builder with the executor service set as specified. */ public DefaultAzureCredentialBuilder executorService(ExecutorService executorService) { this.identityClientOptions.setExecutorService(executorService); return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public DefaultAzureCredentialBuilder additionallyAllowedTenants(String... additionallyAllowedTenants) { this.additionallyAllowedTenants = IdentityUtil.resolveAdditionalTenants(Arrays.asList(additionallyAllowedTenants)); return this; } /** * For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens. * Add the wildcard value "*" to allow the credential to acquire tokens for any tenant the application is installed. * * @param additionallyAllowedTenants the additionally allowed tenants. * @return An updated instance of this builder with the tenant id set as specified. */ @SuppressWarnings("unchecked") public DefaultAzureCredentialBuilder additionallyAllowedTenants(List<String> additionallyAllowedTenants) { this.additionallyAllowedTenants = IdentityUtil.resolveAdditionalTenants(additionallyAllowedTenants); return this; } /** * Specifies a {@link Duration} timeout for developer credentials (such as Azure CLI) that rely on separate process * invocations. * @param duration The {@link Duration} to wait. * @return An updated instance of this builder with the timeout specified. */ /** * Disable instance discovery. Instance discovery is acquiring metadata about an authority from https: * to validate that authority. This may need to be disabled in private cloud or ADFS scenarios. * * @return An updated instance of this builder with instance discovery disabled. */ public DefaultAzureCredentialBuilder disableInstanceDiscovery() { this.identityClientOptions.disableInstanceDisovery(); return this; } /** * Creates new {@link DefaultAzureCredential} with the configured options set. * * @return a {@link DefaultAzureCredential} with the current configurations. * @throws IllegalStateException if clientId and resourceId are both set. */ public DefaultAzureCredential build() { loadFallbackValuesFromEnvironment(); if (managedIdentityClientId != null && managedIdentityResourceId != null) { throw LOGGER.logExceptionAsError( new IllegalStateException("Only one of managedIdentityResourceId and managedIdentityClientId can be specified.")); } if (!CoreUtils.isNullOrEmpty(additionallyAllowedTenants)) { identityClientOptions.setAdditionallyAllowedTenants(additionallyAllowedTenants); } return new DefaultAzureCredential(getCredentialsChain()); } private void loadFallbackValuesFromEnvironment() { Configuration configuration = identityClientOptions.getConfiguration() == null ? Configuration.getGlobalConfiguration().clone() : identityClientOptions.getConfiguration(); tenantId = CoreUtils.isNullOrEmpty(tenantId) ? configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID) : tenantId; managedIdentityClientId = CoreUtils.isNullOrEmpty(managedIdentityClientId) ? configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID) : managedIdentityClientId; } private ArrayList<TokenCredential> getCredentialsChain() { WorkloadIdentityCredential workloadIdentityCredential = getWorkloadIdentityCredentialIfAvailable(); ArrayList<TokenCredential> output = new ArrayList<TokenCredential>(workloadIdentityCredential != null ? 8 : 7); output.add(new EnvironmentCredential(identityClientOptions.clone())); if (workloadIdentityCredential != null) { output.add(workloadIdentityCredential); } output.add(new ManagedIdentityCredential(managedIdentityClientId, managedIdentityResourceId, identityClientOptions.clone())); output.add(new AzureDeveloperCliCredential(tenantId, identityClientOptions.clone())); output.add(new SharedTokenCacheCredential(null, IdentityConstants.DEVELOPER_SINGLE_SIGN_ON_ID, tenantId, identityClientOptions.clone())); output.add(new IntelliJCredential(tenantId, identityClientOptions.clone())); output.add(new AzureCliCredential(tenantId, identityClientOptions.clone())); output.add(new AzurePowerShellCredential(tenantId, identityClientOptions.clone())); return output; } private WorkloadIdentityCredential getWorkloadIdentityCredentialIfAvailable() { Configuration configuration = identityClientOptions.getConfiguration() == null ? Configuration.getGlobalConfiguration().clone() : identityClientOptions.getConfiguration(); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String federatedTokenFilePath = configuration.get(AZURE_FEDERATED_TOKEN_FILE); String azureAuthorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST); String clientId = CoreUtils.isNullOrEmpty(workloadIdentityClientId) ? managedIdentityClientId : workloadIdentityClientId; if (!(CoreUtils.isNullOrEmpty(tenantId) || CoreUtils.isNullOrEmpty(federatedTokenFilePath) || CoreUtils.isNullOrEmpty(clientId) || CoreUtils.isNullOrEmpty(azureAuthorityHost))) { return new WorkloadIdentityCredential(tenantId, clientId, federatedTokenFilePath, identityClientOptions.setAuthorityHost(azureAuthorityHost).clone()); } return null; } }
Should the directory be added back but `TestProxyDownloader.getProxyDirectory()` changes based on being in CI or local?
public void startProxy() { try { String commandLine = "test-proxy"; if (runningLocally()) { commandLine = Paths.get(TestProxyDownloader.getProxyDirectory().toString(), TestProxyUtils.getProxyProcessName()).toString(); } ProcessBuilder builder = new ProcessBuilder(commandLine, "--storage-location", recordingPath.getPath(), "--", "--urls", getProxyUrl().toString()); proxy = builder.start(); HttpURLConnectionHttpClient client = new HttpURLConnectionHttpClient(); HttpRequest request = new HttpRequest(HttpMethod.GET, String.format("%s/admin/isalive", getProxyUrl())); for (int i = 0; i < 10; i++) { HttpResponse response = null; try { response = client.sendSync(request, Context.NONE); if (response != null && response.getStatusCode() == 200) { return; } TestProxyUtils.checkForTestProxyErrors(response); } catch (Exception ignored) { } Thread.sleep(1000); } throw new RuntimeException("Test proxy did not initialize."); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } catch (InterruptedException e) { throw new RuntimeException(e); } }
ProcessBuilder builder = new ProcessBuilder(commandLine, "--storage-location", recordingPath.getPath(), "--", "--urls", getProxyUrl().toString());
public void startProxy() { try { String commandLine = "test-proxy"; if (runningLocally()) { commandLine = Paths.get(TestProxyDownloader.getProxyDirectory().toString(), TestProxyUtils.getProxyProcessName()).toString(); } ProcessBuilder builder = new ProcessBuilder(commandLine, "--storage-location", recordingPath.getPath(), "--", "--urls", getProxyUrl().toString()); Map<String, String> environment = builder.environment(); environment.put("LOGGING__LOGLEVEL", "Information"); environment.put("LOGGING__LOGLEVEL__MICROSOFT", "Warning"); environment.put("LOGGING__LOGLEVEL__DEFAULT", "Information"); proxy = builder.start(); HttpURLConnectionHttpClient client = new HttpURLConnectionHttpClient(); HttpRequest request = new HttpRequest(HttpMethod.GET, String.format("%s/admin/isalive", getProxyUrl())); for (int i = 0; i < 10; i++) { HttpResponse response = null; try { response = client.sendSync(request, Context.NONE); if (response != null && response.getStatusCode() == 200) { return; } TestProxyUtils.checkForTestProxyErrors(response); } catch (Exception ignored) { } Thread.sleep(1000); } throw new RuntimeException("Test proxy did not initialize."); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } catch (InterruptedException e) { throw new RuntimeException(e); } }
class TestProxyManager { private static final ClientLogger LOGGER = new ClientLogger(TestProxyManager.class); private final File recordingPath; private Process proxy; private static final AtomicInteger PORT_COUNTER = new AtomicInteger(5000); private URL proxyUrl; /** * Construct a {@link TestProxyManager} for controlling the external test proxy. * @param recordingPath The local path in the file system where recordings are saved. */ public TestProxyManager(File recordingPath) { this.recordingPath = recordingPath; Runtime.getRuntime().addShutdownHook(new Thread(this::stopProxy)); if (runningLocally()) { TestProxyDownloader.installTestProxy(); } } /** * Start an instance of the test proxy. * @throws UncheckedIOException There was an issue communicating with the proxy. * @throws RuntimeException There was an issue starting the proxy process. */ /** * Stop the running instance of the test proxy. */ public void stopProxy() { if (proxy.isAlive()) { proxy.destroy(); } } /** * Get the proxy URL. * * @return A string containing the proxy URL. * @throws RuntimeException The proxy URL could not be constructed. */ public URL getProxyUrl() { if (proxyUrl != null) { return proxyUrl; } UrlBuilder builder = new UrlBuilder(); builder.setHost("localhost"); builder.setScheme("http"); builder.setPort(PORT_COUNTER.getAndIncrement()); try { proxyUrl = builder.toUrl(); } catch (MalformedURLException e) { throw new RuntimeException(e); } return proxyUrl; } /** * Checks the environment variables commonly set in CI to determine if the run is local. * @return True if the run is local. */ private boolean runningLocally() { return Configuration.getGlobalConfiguration().get("TF_BUILD") == null && Configuration.getGlobalConfiguration().get("CI") == null; } }
class TestProxyManager { private static final ClientLogger LOGGER = new ClientLogger(TestProxyManager.class); private final File recordingPath; private Process proxy; private static final AtomicInteger PORT_COUNTER = new AtomicInteger(5000); private URL proxyUrl; /** * Construct a {@link TestProxyManager} for controlling the external test proxy. * @param recordingPath The local path in the file system where recordings are saved. */ public TestProxyManager(File recordingPath) { this.recordingPath = recordingPath; Runtime.getRuntime().addShutdownHook(new Thread(this::stopProxy)); if (runningLocally()) { TestProxyDownloader.installTestProxy(); } } /** * Start an instance of the test proxy. * @throws UncheckedIOException There was an issue communicating with the proxy. * @throws RuntimeException There was an issue starting the proxy process. */ /** * Stop the running instance of the test proxy. */ public void stopProxy() { if (proxy.isAlive()) { proxy.destroy(); } } /** * Get the proxy URL. * * @return A string containing the proxy URL. * @throws RuntimeException The proxy URL could not be constructed. */ public URL getProxyUrl() { if (proxyUrl != null) { return proxyUrl; } UrlBuilder builder = new UrlBuilder(); builder.setHost("localhost"); builder.setScheme("http"); builder.setPort(PORT_COUNTER.getAndIncrement()); try { proxyUrl = builder.toUrl(); } catch (MalformedURLException e) { throw new RuntimeException(e); } return proxyUrl; } /** * Checks the environment variables commonly set in CI to determine if the run is local. * @return True if the run is local. */ private boolean runningLocally() { return Configuration.getGlobalConfiguration().get("TF_BUILD") == null && Configuration.getGlobalConfiguration().get("CI") == null; } }
Good catch, long term I think we need to add some more metadata to `BinaryDataContent` where we don't need to do all this type checking as it breaks when new types are added.
private RequestBody toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HttpHeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); BinaryDataContent content = BinaryDataHelper.getContent(bodyContent); if (content instanceof ByteArrayContent || content instanceof StringContent || content instanceof SerializableContent || content instanceof ByteBufferContent) { return RequestBody.create(content.toBytes(), mediaType); } else { long effectiveContentLength = getRequestContentLength(content, headers); if (content instanceof InputStreamContent) { return new OkHttpInputStreamRequestBody( (InputStreamContent) content, effectiveContentLength, mediaType); } else if (content instanceof FileContent) { return new OkHttpFileRequestBody((FileContent) content, effectiveContentLength, mediaType); } else { return new OkHttpFluxRequestBody( content, effectiveContentLength, mediaType, httpClient.callTimeoutMillis()); } } }
|| content instanceof ByteBufferContent) {
private RequestBody toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HttpHeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); BinaryDataContent content = BinaryDataHelper.getContent(bodyContent); if (content instanceof ByteArrayContent || content instanceof StringContent || content instanceof SerializableContent || content instanceof ByteBufferContent) { return RequestBody.create(content.toBytes(), mediaType); } else { long effectiveContentLength = getRequestContentLength(content, headers); if (content instanceof InputStreamContent) { return new OkHttpInputStreamRequestBody( (InputStreamContent) content, effectiveContentLength, mediaType); } else if (content instanceof FileContent) { return new OkHttpFileRequestBody((FileContent) content, effectiveContentLength, mediaType); } else { return new OkHttpFluxRequestBody( content, effectiveContentLength, mediaType, httpClient.callTimeoutMillis()); } } }
class OkHttpAsyncHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); private static final String AZURE_EAGERLY_READ_RESPONSE = "azure-eagerly-read-response"; private static final String AZURE_IGNORE_RESPONSE_BODY = "azure-ignore-response-body"; private static final String AZURE_EAGERLY_CONVERT_HEADERS = "azure-eagerly-convert-headers"; final OkHttpClient httpClient; OkHttpAsyncHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Mono<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override public Mono<HttpResponse> send(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData(AZURE_EAGERLY_READ_RESPONSE).orElse(false); boolean ignoreResponseBody = (boolean) context.getData(AZURE_IGNORE_RESPONSE_BODY).orElse(false); boolean eagerlyConvertHeaders = (boolean) context.getData(AZURE_EAGERLY_CONVERT_HEADERS).orElse(false); ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); return Mono.create(sink -> sink.onRequest(value -> { Mono.fromCallable(() -> toOkHttpRequest(request, progressReporter)) .subscribe(okHttpRequest -> { try { Call call = httpClient.newCall(okHttpRequest); call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders)); sink.onCancel(call::cancel); } catch (Exception ex) { sink.error(ex); } }, sink::error); })); } @Override public HttpResponse sendSync(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData(AZURE_EAGERLY_READ_RESPONSE).orElse(false); boolean ignoreResponseBody = (boolean) context.getData(AZURE_IGNORE_RESPONSE_BODY).orElse(false); boolean eagerlyConvertHeaders = (boolean) context.getData(AZURE_EAGERLY_CONVERT_HEADERS).orElse(false); ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); Request okHttpRequest = toOkHttpRequest(request, progressReporter); try { Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toHttpResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } /** * Converts the given azure-core request to okhttp request. * * @param request the azure-core request * @param progressReporter the {@link ProgressReporter}. Can be null. * @return the okhttp request */ private okhttp3.Request toOkHttpRequest(HttpRequest request, ProgressReporter progressReporter) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBodyAsBinaryData(), request.getHeaders()); if (progressReporter != null) { okHttpRequestBody = new OkHttpProgressReportingRequestBody(okHttpRequestBody, progressReporter); } return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody) .build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * @return the Mono emitting okhttp request */ private static long getRequestContentLength(BinaryDataContent content, HttpHeaders headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HttpHeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private static HttpResponse toHttpResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { /* * Use a buffered response when we are eagerly reading the response from the network and the body isn't * empty. */ if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpAsyncBufferedResponse(response, request, bytes, eagerlyConvertHeaders); } } else { return new OkHttpAsyncResponse(response, request, eagerlyConvertHeaders); } } private static class OkHttpCallback implements okhttp3.Callback { private final MonoSink<HttpResponse> sink; private final HttpRequest request; private final boolean eagerlyReadResponse; private final boolean ignoreResponseBody; private final boolean eagerlyConvertHeaders; OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) { this.sink = sink; this.request = request; this.eagerlyReadResponse = eagerlyReadResponse; this.ignoreResponseBody = ignoreResponseBody; this.eagerlyConvertHeaders = eagerlyConvertHeaders; } @SuppressWarnings("NullableProblems") @Override public void onFailure(okhttp3.Call call, IOException e) { if (e.getSuppressed().length == 1) { sink.error(e.getSuppressed()[0]); } else { sink.error(e); } } @SuppressWarnings("NullableProblems") @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) { try { sink.success(toHttpResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders)); } catch (IOException ex) { sink.error(ex); } } } }
class OkHttpAsyncHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); private static final String AZURE_EAGERLY_READ_RESPONSE = "azure-eagerly-read-response"; private static final String AZURE_IGNORE_RESPONSE_BODY = "azure-ignore-response-body"; private static final String AZURE_EAGERLY_CONVERT_HEADERS = "azure-eagerly-convert-headers"; final OkHttpClient httpClient; OkHttpAsyncHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Mono<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override public Mono<HttpResponse> send(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData(AZURE_EAGERLY_READ_RESPONSE).orElse(false); boolean ignoreResponseBody = (boolean) context.getData(AZURE_IGNORE_RESPONSE_BODY).orElse(false); boolean eagerlyConvertHeaders = (boolean) context.getData(AZURE_EAGERLY_CONVERT_HEADERS).orElse(false); ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); return Mono.create(sink -> sink.onRequest(value -> { Mono.fromCallable(() -> toOkHttpRequest(request, progressReporter)) .subscribe(okHttpRequest -> { try { Call call = httpClient.newCall(okHttpRequest); call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders)); sink.onCancel(call::cancel); } catch (Exception ex) { sink.error(ex); } }, sink::error); })); } @Override public HttpResponse sendSync(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData(AZURE_EAGERLY_READ_RESPONSE).orElse(false); boolean ignoreResponseBody = (boolean) context.getData(AZURE_IGNORE_RESPONSE_BODY).orElse(false); boolean eagerlyConvertHeaders = (boolean) context.getData(AZURE_EAGERLY_CONVERT_HEADERS).orElse(false); ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); Request okHttpRequest = toOkHttpRequest(request, progressReporter); try { Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toHttpResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } /** * Converts the given azure-core request to okhttp request. * * @param request the azure-core request * @param progressReporter the {@link ProgressReporter}. Can be null. * @return the okhttp request */ private okhttp3.Request toOkHttpRequest(HttpRequest request, ProgressReporter progressReporter) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBodyAsBinaryData(), request.getHeaders()); if (progressReporter != null) { okHttpRequestBody = new OkHttpProgressReportingRequestBody(okHttpRequestBody, progressReporter); } return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody) .build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * @return the Mono emitting okhttp request */ private static long getRequestContentLength(BinaryDataContent content, HttpHeaders headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HttpHeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private static HttpResponse toHttpResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { /* * Use a buffered response when we are eagerly reading the response from the network and the body isn't * empty. */ if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpAsyncBufferedResponse(response, request, bytes, eagerlyConvertHeaders); } } else { return new OkHttpAsyncResponse(response, request, eagerlyConvertHeaders); } } private static class OkHttpCallback implements okhttp3.Callback { private final MonoSink<HttpResponse> sink; private final HttpRequest request; private final boolean eagerlyReadResponse; private final boolean ignoreResponseBody; private final boolean eagerlyConvertHeaders; OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) { this.sink = sink; this.request = request; this.eagerlyReadResponse = eagerlyReadResponse; this.ignoreResponseBody = ignoreResponseBody; this.eagerlyConvertHeaders = eagerlyConvertHeaders; } @SuppressWarnings("NullableProblems") @Override public void onFailure(okhttp3.Call call, IOException e) { if (e.getSuppressed().length == 1) { sink.error(e.getSuppressed()[0]); } else { sink.error(e); } } @SuppressWarnings("NullableProblems") @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) { try { sink.success(toHttpResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders)); } catch (IOException ex) { sink.error(ex); } } } }
reading my thoughts - https://github.com/Azure/azure-sdk-for-java/issues/34501
private RequestBody toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HttpHeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); BinaryDataContent content = BinaryDataHelper.getContent(bodyContent); if (content instanceof ByteArrayContent || content instanceof StringContent || content instanceof SerializableContent || content instanceof ByteBufferContent) { return RequestBody.create(content.toBytes(), mediaType); } else { long effectiveContentLength = getRequestContentLength(content, headers); if (content instanceof InputStreamContent) { return new OkHttpInputStreamRequestBody( (InputStreamContent) content, effectiveContentLength, mediaType); } else if (content instanceof FileContent) { return new OkHttpFileRequestBody((FileContent) content, effectiveContentLength, mediaType); } else { return new OkHttpFluxRequestBody( content, effectiveContentLength, mediaType, httpClient.callTimeoutMillis()); } } }
|| content instanceof ByteBufferContent) {
private RequestBody toOkHttpRequestBody(BinaryData bodyContent, HttpHeaders headers) { if (bodyContent == null) { return EMPTY_REQUEST_BODY; } String contentType = headers.getValue(HttpHeaderName.CONTENT_TYPE); MediaType mediaType = (contentType == null) ? null : MediaType.parse(contentType); BinaryDataContent content = BinaryDataHelper.getContent(bodyContent); if (content instanceof ByteArrayContent || content instanceof StringContent || content instanceof SerializableContent || content instanceof ByteBufferContent) { return RequestBody.create(content.toBytes(), mediaType); } else { long effectiveContentLength = getRequestContentLength(content, headers); if (content instanceof InputStreamContent) { return new OkHttpInputStreamRequestBody( (InputStreamContent) content, effectiveContentLength, mediaType); } else if (content instanceof FileContent) { return new OkHttpFileRequestBody((FileContent) content, effectiveContentLength, mediaType); } else { return new OkHttpFluxRequestBody( content, effectiveContentLength, mediaType, httpClient.callTimeoutMillis()); } } }
class OkHttpAsyncHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); private static final String AZURE_EAGERLY_READ_RESPONSE = "azure-eagerly-read-response"; private static final String AZURE_IGNORE_RESPONSE_BODY = "azure-ignore-response-body"; private static final String AZURE_EAGERLY_CONVERT_HEADERS = "azure-eagerly-convert-headers"; final OkHttpClient httpClient; OkHttpAsyncHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Mono<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override public Mono<HttpResponse> send(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData(AZURE_EAGERLY_READ_RESPONSE).orElse(false); boolean ignoreResponseBody = (boolean) context.getData(AZURE_IGNORE_RESPONSE_BODY).orElse(false); boolean eagerlyConvertHeaders = (boolean) context.getData(AZURE_EAGERLY_CONVERT_HEADERS).orElse(false); ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); return Mono.create(sink -> sink.onRequest(value -> { Mono.fromCallable(() -> toOkHttpRequest(request, progressReporter)) .subscribe(okHttpRequest -> { try { Call call = httpClient.newCall(okHttpRequest); call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders)); sink.onCancel(call::cancel); } catch (Exception ex) { sink.error(ex); } }, sink::error); })); } @Override public HttpResponse sendSync(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData(AZURE_EAGERLY_READ_RESPONSE).orElse(false); boolean ignoreResponseBody = (boolean) context.getData(AZURE_IGNORE_RESPONSE_BODY).orElse(false); boolean eagerlyConvertHeaders = (boolean) context.getData(AZURE_EAGERLY_CONVERT_HEADERS).orElse(false); ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); Request okHttpRequest = toOkHttpRequest(request, progressReporter); try { Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toHttpResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } /** * Converts the given azure-core request to okhttp request. * * @param request the azure-core request * @param progressReporter the {@link ProgressReporter}. Can be null. * @return the okhttp request */ private okhttp3.Request toOkHttpRequest(HttpRequest request, ProgressReporter progressReporter) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBodyAsBinaryData(), request.getHeaders()); if (progressReporter != null) { okHttpRequestBody = new OkHttpProgressReportingRequestBody(okHttpRequestBody, progressReporter); } return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody) .build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * @return the Mono emitting okhttp request */ private static long getRequestContentLength(BinaryDataContent content, HttpHeaders headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HttpHeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private static HttpResponse toHttpResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { /* * Use a buffered response when we are eagerly reading the response from the network and the body isn't * empty. */ if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpAsyncBufferedResponse(response, request, bytes, eagerlyConvertHeaders); } } else { return new OkHttpAsyncResponse(response, request, eagerlyConvertHeaders); } } private static class OkHttpCallback implements okhttp3.Callback { private final MonoSink<HttpResponse> sink; private final HttpRequest request; private final boolean eagerlyReadResponse; private final boolean ignoreResponseBody; private final boolean eagerlyConvertHeaders; OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) { this.sink = sink; this.request = request; this.eagerlyReadResponse = eagerlyReadResponse; this.ignoreResponseBody = ignoreResponseBody; this.eagerlyConvertHeaders = eagerlyConvertHeaders; } @SuppressWarnings("NullableProblems") @Override public void onFailure(okhttp3.Call call, IOException e) { if (e.getSuppressed().length == 1) { sink.error(e.getSuppressed()[0]); } else { sink.error(e); } } @SuppressWarnings("NullableProblems") @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) { try { sink.success(toHttpResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders)); } catch (IOException ex) { sink.error(ex); } } } }
class OkHttpAsyncHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(OkHttpAsyncHttpClient.class); private static final byte[] EMPTY_BODY = new byte[0]; private static final RequestBody EMPTY_REQUEST_BODY = RequestBody.create(EMPTY_BODY); private static final String AZURE_EAGERLY_READ_RESPONSE = "azure-eagerly-read-response"; private static final String AZURE_IGNORE_RESPONSE_BODY = "azure-ignore-response-body"; private static final String AZURE_EAGERLY_CONVERT_HEADERS = "azure-eagerly-convert-headers"; final OkHttpClient httpClient; OkHttpAsyncHttpClient(OkHttpClient httpClient) { this.httpClient = httpClient; } @Override public Mono<HttpResponse> send(HttpRequest request) { return send(request, Context.NONE); } @Override public Mono<HttpResponse> send(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData(AZURE_EAGERLY_READ_RESPONSE).orElse(false); boolean ignoreResponseBody = (boolean) context.getData(AZURE_IGNORE_RESPONSE_BODY).orElse(false); boolean eagerlyConvertHeaders = (boolean) context.getData(AZURE_EAGERLY_CONVERT_HEADERS).orElse(false); ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); return Mono.create(sink -> sink.onRequest(value -> { Mono.fromCallable(() -> toOkHttpRequest(request, progressReporter)) .subscribe(okHttpRequest -> { try { Call call = httpClient.newCall(okHttpRequest); call.enqueue(new OkHttpCallback(sink, request, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders)); sink.onCancel(call::cancel); } catch (Exception ex) { sink.error(ex); } }, sink::error); })); } @Override public HttpResponse sendSync(HttpRequest request, Context context) { boolean eagerlyReadResponse = (boolean) context.getData(AZURE_EAGERLY_READ_RESPONSE).orElse(false); boolean ignoreResponseBody = (boolean) context.getData(AZURE_IGNORE_RESPONSE_BODY).orElse(false); boolean eagerlyConvertHeaders = (boolean) context.getData(AZURE_EAGERLY_CONVERT_HEADERS).orElse(false); ProgressReporter progressReporter = Contexts.with(context).getHttpRequestProgressReporter(); Request okHttpRequest = toOkHttpRequest(request, progressReporter); try { Response okHttpResponse = httpClient.newCall(okHttpRequest).execute(); return toHttpResponse(request, okHttpResponse, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders); } catch (IOException e) { throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } /** * Converts the given azure-core request to okhttp request. * * @param request the azure-core request * @param progressReporter the {@link ProgressReporter}. Can be null. * @return the okhttp request */ private okhttp3.Request toOkHttpRequest(HttpRequest request, ProgressReporter progressReporter) { Request.Builder requestBuilder = new Request.Builder() .url(request.getUrl()); if (request.getHeaders() != null) { for (HttpHeader hdr : request.getHeaders()) { hdr.getValuesList().forEach(value -> requestBuilder.addHeader(hdr.getName(), value)); } } if (request.getHttpMethod() == HttpMethod.GET) { return requestBuilder.get().build(); } else if (request.getHttpMethod() == HttpMethod.HEAD) { return requestBuilder.head().build(); } RequestBody okHttpRequestBody = toOkHttpRequestBody(request.getBodyAsBinaryData(), request.getHeaders()); if (progressReporter != null) { okHttpRequestBody = new OkHttpProgressReportingRequestBody(okHttpRequestBody, progressReporter); } return requestBuilder.method(request.getHttpMethod().toString(), okHttpRequestBody) .build(); } /** * Create a Mono of okhttp3.RequestBody from the given BinaryData. * * @param bodyContent The request body content * @param headers the headers associated with the original request * @return the Mono emitting okhttp request */ private static long getRequestContentLength(BinaryDataContent content, HttpHeaders headers) { Long contentLength = content.getLength(); if (contentLength == null) { String contentLengthHeaderValue = headers.getValue(HttpHeaderName.CONTENT_LENGTH); if (contentLengthHeaderValue != null) { contentLength = Long.parseLong(contentLengthHeaderValue); } else { contentLength = -1L; } } return contentLength; } private static HttpResponse toHttpResponse(HttpRequest request, okhttp3.Response response, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) throws IOException { /* * Use a buffered response when we are eagerly reading the response from the network and the body isn't * empty. */ if (eagerlyReadResponse || ignoreResponseBody) { try (ResponseBody body = response.body()) { byte[] bytes = (body != null) ? body.bytes() : EMPTY_BODY; return new OkHttpAsyncBufferedResponse(response, request, bytes, eagerlyConvertHeaders); } } else { return new OkHttpAsyncResponse(response, request, eagerlyConvertHeaders); } } private static class OkHttpCallback implements okhttp3.Callback { private final MonoSink<HttpResponse> sink; private final HttpRequest request; private final boolean eagerlyReadResponse; private final boolean ignoreResponseBody; private final boolean eagerlyConvertHeaders; OkHttpCallback(MonoSink<HttpResponse> sink, HttpRequest request, boolean eagerlyReadResponse, boolean ignoreResponseBody, boolean eagerlyConvertHeaders) { this.sink = sink; this.request = request; this.eagerlyReadResponse = eagerlyReadResponse; this.ignoreResponseBody = ignoreResponseBody; this.eagerlyConvertHeaders = eagerlyConvertHeaders; } @SuppressWarnings("NullableProblems") @Override public void onFailure(okhttp3.Call call, IOException e) { if (e.getSuppressed().length == 1) { sink.error(e.getSuppressed()[0]); } else { sink.error(e); } } @SuppressWarnings("NullableProblems") @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) { try { sink.success(toHttpResponse(request, response, eagerlyReadResponse, ignoreResponseBody, eagerlyConvertHeaders)); } catch (IOException ex) { sink.error(ex); } } } }
we can use the MockTokenCredential here.
public void beforeTest() { dataCollectionEndpoint = Configuration.getGlobalConfiguration().get("AZURE_MONITOR_DCE", "https: dataCollectionRuleId = Configuration.getGlobalConfiguration().get("AZURE_MONITOR_DCR_ID", "dcr-a64851bc17714f0483d1e96b5d84953b"); streamName = "Custom-MyTableRawData"; LogsIngestionClientBuilder clientBuilder = new LogsIngestionClientBuilder() .retryPolicy(new RetryPolicy(new RetryStrategy() { @Override public int getMaxRetries() { return 0; } @Override public Duration calculateRetryDelay(int i) { return null; } })); if (getTestMode() == TestMode.PLAYBACK) { clientBuilder .credential(request -> Mono.just(new AccessToken("fakeToken", OffsetDateTime.now().plusDays(1)))) .httpClient(interceptorManager.getPlaybackClient()); } else if (getTestMode() == TestMode.RECORD) { clientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(getCredential()); } else if (getTestMode() == TestMode.LIVE) { clientBuilder.credential(getCredential()); } this.clientBuilder = clientBuilder .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(dataCollectionEndpoint); }
.credential(request -> Mono.just(new AccessToken("fakeToken", OffsetDateTime.now().plusDays(1))))
public void beforeTest() { dataCollectionEndpoint = Configuration.getGlobalConfiguration().get("AZURE_MONITOR_DCE", "https: dataCollectionRuleId = Configuration.getGlobalConfiguration().get("AZURE_MONITOR_DCR_ID", "dcr-a64851bc17714f0483d1e96b5d84953b"); streamName = "Custom-MyTableRawData"; LogsIngestionClientBuilder clientBuilder = new LogsIngestionClientBuilder() .retryPolicy(new RetryPolicy(new RetryStrategy() { @Override public int getMaxRetries() { return 0; } @Override public Duration calculateRetryDelay(int i) { return null; } })); if (getTestMode() == TestMode.PLAYBACK) { interceptorManager.addMatchers(Arrays.asList(new BodilessMatcher())); clientBuilder .credential(new MockTokenCredential()) .httpClient(interceptorManager.getPlaybackClient()); } else if (getTestMode() == TestMode.RECORD) { clientBuilder .addPolicy(interceptorManager.getRecordPolicy()) .credential(new DefaultAzureCredentialBuilder().build()); } else if (getTestMode() == TestMode.LIVE) { clientBuilder.credential(new DefaultAzureCredentialBuilder().build()); } this.clientBuilder = clientBuilder .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(dataCollectionEndpoint); }
class LogsIngestionTestBase extends TestProxyTestBase { protected LogsIngestionClientBuilder clientBuilder; protected String dataCollectionEndpoint; protected String dataCollectionRuleId; protected String streamName; @Override protected TokenCredential getCredential() { return new ClientSecretCredentialBuilder() .clientId(Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)) .clientSecret(Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_SECRET)) .tenantId(Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_TENANT_ID)) .build(); } public class BatchCountPolicy implements HttpPipelinePolicy { private final AtomicInteger counter; BatchCountPolicy(AtomicInteger counter) { this.counter = counter; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { counter.incrementAndGet(); return next.process(); } @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { counter.incrementAndGet(); return next.processSync(); } @Override public HttpPipelinePosition getPipelinePosition() { return HttpPipelinePosition.PER_CALL; } } public class PartialFailurePolicy implements HttpPipelinePolicy { private final AtomicInteger counter; private final AtomicBoolean changeDcrId = new AtomicBoolean(); PartialFailurePolicy(AtomicInteger counter) { this.counter = counter; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { process(context); return next.process(); } @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { process(context); return next.processSync(); } private void process(HttpPipelineCallContext context) { counter.incrementAndGet(); if (changeDcrId.get()) { String url = context.getHttpRequest().getUrl().toString() .replace(dataCollectionRuleId, "dcr-id"); context.getHttpRequest().setUrl(url); changeDcrId.set(false); } else { changeDcrId.set(true); } } @Override public HttpPipelinePosition getPipelinePosition() { return HttpPipelinePosition.PER_CALL; } } public static List<Object> getObjects(int logsCount) { List<Object> logs = new ArrayList<>(); for (int i = 0; i < logsCount; i++) { LogData logData = new LogData() .setTime(OffsetDateTime.parse("2022-01-01T00:00:00+07:00")) .setExtendedColumn("test" + i) .setAdditionalContext("additional logs context"); logs.add(logData); } return logs; } public static class LogsCountPolicy implements HttpPipelinePolicy { private AtomicLong totalLogsCount = new AtomicLong(); @Override public Mono<HttpResponse> process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { BinaryData bodyAsBinaryData = httpPipelineCallContext.getHttpRequest().getBodyAsBinaryData(); byte[] requestBytes = unzipRequestBody(bodyAsBinaryData); List<Object> logs = JsonSerializerProviders.createInstance(true) .deserializeFromBytes(requestBytes, new TypeReference<List<Object>>() { }); totalLogsCount.addAndGet(logs.size()); return httpPipelineNextPolicy.process(); } public long getTotalLogsCount() { return this.totalLogsCount.get(); } } public static class DataValidationPolicy implements HttpPipelinePolicy { private final String expectedJson; public DataValidationPolicy(List<Object> inputData) { this.expectedJson = new String(JsonSerializerProviders.createInstance(true).serializeToBytes(inputData)); } @Override public Mono<HttpResponse> process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { BinaryData bodyAsBinaryData = httpPipelineCallContext.getHttpRequest().getBodyAsBinaryData(); String actualJson = new String(unzipRequestBody(bodyAsBinaryData)); assertEquals(expectedJson, actualJson); return httpPipelineNextPolicy.process(); } } private static byte[] unzipRequestBody(BinaryData bodyAsBinaryData) { try { byte[] buffer = new byte[1024]; GZIPInputStream gZIPInputStream = new GZIPInputStream(new ByteArrayInputStream(bodyAsBinaryData.toBytes())); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int bytesRead; while ((bytesRead = gZIPInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); } gZIPInputStream.close(); outputStream.close(); return outputStream.toByteArray(); } catch (IOException exception) { System.out.println("Failed to unzip data"); } return null; } }
class LogsIngestionTestBase extends TestProxyTestBase { protected LogsIngestionClientBuilder clientBuilder; protected String dataCollectionEndpoint; protected String dataCollectionRuleId; protected String streamName; @Override public class BatchCountPolicy implements HttpPipelinePolicy { private final AtomicInteger counter; BatchCountPolicy(AtomicInteger counter) { this.counter = counter; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { counter.incrementAndGet(); return next.process(); } @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { counter.incrementAndGet(); return next.processSync(); } @Override public HttpPipelinePosition getPipelinePosition() { return HttpPipelinePosition.PER_CALL; } } public class PartialFailurePolicy implements HttpPipelinePolicy { private final AtomicInteger counter; private final AtomicBoolean changeDcrId = new AtomicBoolean(); PartialFailurePolicy(AtomicInteger counter) { this.counter = counter; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { process(context); return next.process(); } @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { process(context); return next.processSync(); } private void process(HttpPipelineCallContext context) { counter.incrementAndGet(); if (changeDcrId.get()) { String url = context.getHttpRequest().getUrl().toString() .replace(dataCollectionRuleId, "dcr-id"); context.getHttpRequest().setUrl(url); changeDcrId.set(false); } else { changeDcrId.set(true); } } @Override public HttpPipelinePosition getPipelinePosition() { return HttpPipelinePosition.PER_CALL; } } public static List<Object> getObjects(int logsCount) { List<Object> logs = new ArrayList<>(); for (int i = 0; i < logsCount; i++) { LogData logData = new LogData() .setTime(OffsetDateTime.parse("2022-01-01T00:00:00+07:00")) .setExtendedColumn("test" + i) .setAdditionalContext("additional logs context"); logs.add(logData); } return logs; } public static class LogsCountPolicy implements HttpPipelinePolicy { private AtomicLong totalLogsCount = new AtomicLong(); @Override public Mono<HttpResponse> process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { BinaryData bodyAsBinaryData = httpPipelineCallContext.getHttpRequest().getBodyAsBinaryData(); byte[] requestBytes = unzipRequestBody(bodyAsBinaryData); List<Object> logs = JsonSerializerProviders.createInstance(true) .deserializeFromBytes(requestBytes, new TypeReference<List<Object>>() { }); totalLogsCount.addAndGet(logs.size()); return httpPipelineNextPolicy.process(); } public long getTotalLogsCount() { return this.totalLogsCount.get(); } } public static class DataValidationPolicy implements HttpPipelinePolicy { private final String expectedJson; public DataValidationPolicy(List<Object> inputData) { this.expectedJson = new String(JsonSerializerProviders.createInstance(true).serializeToBytes(inputData)); } @Override public Mono<HttpResponse> process(HttpPipelineCallContext httpPipelineCallContext, HttpPipelineNextPolicy httpPipelineNextPolicy) { BinaryData bodyAsBinaryData = httpPipelineCallContext.getHttpRequest().getBodyAsBinaryData(); String actualJson = new String(unzipRequestBody(bodyAsBinaryData)); assertEquals(expectedJson, actualJson); return httpPipelineNextPolicy.process(); } } private static byte[] unzipRequestBody(BinaryData bodyAsBinaryData) { try { byte[] buffer = new byte[1024]; GZIPInputStream gZIPInputStream = new GZIPInputStream(new ByteArrayInputStream(bodyAsBinaryData.toBytes())); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int bytesRead; while ((bytesRead = gZIPInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); } gZIPInputStream.close(); outputStream.close(); return outputStream.toByteArray(); } catch (IOException exception) { System.out.println("Failed to unzip data"); } return null; } }
nit: would be nice to have utils that return random in core tests and checkstyle warn on random usage in tests
private static void readWithCallback(AsynchronousByteChannel channel, ByteBuffer aggregator, CountDownLatch latch) { ByteBuffer buffer = ByteBuffer.allocate(1 + ThreadLocalRandom.current().nextInt(127)); channel.read(buffer, "foo", new CompletionHandler<Integer, String>() { @Override public void completed(Integer result, String attachment) { assertEquals("foo", attachment); if (result >= 0) { buffer.flip(); aggregator.put(buffer); readWithCallback(channel, aggregator, latch); } else { latch.countDown(); } } @Override public void failed(Throwable exc, String attachment) { latch.countDown(); fail("Unexpected failure"); } }); }
ByteBuffer buffer = ByteBuffer.allocate(1 + ThreadLocalRandom.current().nextInt(127));
private static void readWithCallback(AsynchronousByteChannel channel, ByteBuffer aggregator, CountDownLatch latch) { ByteBuffer buffer = ByteBuffer.allocate(1 + ThreadLocalRandom.current().nextInt(127)); channel.read(buffer, "foo", new CompletionHandler<Integer, String>() { @Override public void completed(Integer result, String attachment) { assertEquals("foo", attachment); if (result >= 0) { buffer.flip(); aggregator.put(buffer); readWithCallback(channel, aggregator, latch); } else { latch.countDown(); } } @Override public void failed(Throwable exc, String attachment) { latch.countDown(); fail("Unexpected failure"); } }); }
class AsynchronousFileChannelAdapterTest { @Test public void closeDelegates() throws IOException { AtomicInteger closeCalls = new AtomicInteger(); AsynchronousFileChannel fileChannelMock = new MockAsynchronousFileChannel() { @Override public void close() throws IOException { closeCalls.incrementAndGet(); super.close(); } }; AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.close(); assertEquals(1, closeCalls.get()); } @Test public void isOpenDelegates() { AtomicInteger openCalls = new AtomicInteger(); AsynchronousFileChannel fileChannelMock = new MockAsynchronousFileChannel() { @Override public boolean isOpen() { return openCalls.getAndIncrement() == 0; } }; AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); assertTrue(channel.isOpen()); assertFalse(channel.isOpen()); assertEquals(2, openCalls.get()); } @Test public void testReadWithCallback() throws IOException, InterruptedException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForReading(data); ByteBuffer readData = ByteBuffer.allocate(data.length); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.READ), 0)) { CountDownLatch latch = new CountDownLatch(1); readWithCallback(channel, readData, latch); latch.await(60, TimeUnit.SECONDS); } readData.flip(); assertArraysEqual(data, readData.array()); } @Test public void testReadWithCallbackAndOffset() throws IOException, InterruptedException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForReading(data); int offset = 117; ByteBuffer readData = ByteBuffer.allocate(data.length - offset); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.READ), offset)) { CountDownLatch latch = new CountDownLatch(1); readWithCallback(channel, readData, latch); latch.await(60, TimeUnit.SECONDS); } readData.flip(); assertArraysEqual(data, offset, data.length - offset, readData.array(), data.length - offset); } @Test public void testReadWithFuture() throws IOException, InterruptedException, ExecutionException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForReading(data); ByteBuffer readData = ByteBuffer.allocate(data.length); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.READ), 0)) { int read; do { ByteBuffer buffer = ByteBuffer.allocate(1 + ThreadLocalRandom.current().nextInt(127)); read = channel.read(buffer).get(); buffer.flip(); readData.put(buffer); } while (read >= 0); } readData.flip(); assertArraysEqual(data, readData.array()); } @Test public void testReadWithWithFutureAndOffset() throws IOException, InterruptedException, ExecutionException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForReading(data); int offset = 117; ByteBuffer readData = ByteBuffer.allocate(data.length - offset); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.READ), offset)) { int read; do { ByteBuffer buffer = ByteBuffer.allocate(1 + ThreadLocalRandom.current().nextInt(127)); read = channel.read(buffer).get(); buffer.flip(); readData.put(buffer); } while (read >= 0); } readData.flip(); assertArraysEqual(data, offset, data.length - offset, readData.array(), data.length - offset); } @Test public void testWriteWithCallback() throws IOException, InterruptedException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForWriting(); ByteBuffer writeData = ByteBuffer.wrap(data); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0)) { CountDownLatch latch = new CountDownLatch(1); writeWithCallback(channel, writeData, latch); latch.await(60, TimeUnit.SECONDS); } assertArraysEqual(data, Files.readAllBytes(tempFile)); } @Test public void testWriteWithCallbackAndOffset() throws IOException, InterruptedException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForWriting(); int offset = 117; ByteBuffer expectedData = ByteBuffer.allocate(data.length + offset); expectedData.put(new byte[offset]); expectedData.put(data); expectedData.flip(); ByteBuffer writeData = ByteBuffer.wrap(data); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), offset)) { CountDownLatch latch = new CountDownLatch(1); writeWithCallback(channel, writeData, latch); latch.await(60, TimeUnit.SECONDS); } assertArraysEqual(expectedData.array(), Files.readAllBytes(tempFile)); } private static void writeWithCallback(AsynchronousByteChannel channel, ByteBuffer data, CountDownLatch latch) { if (!data.hasRemaining()) { latch.countDown(); return; } byte[] buffer = new byte[Math.min(1 + ThreadLocalRandom.current().nextInt(127), data.remaining())]; data.get(buffer); channel.write(ByteBuffer.wrap(buffer), "foo", new CompletionHandler<Integer, String>() { @Override public void completed(Integer result, String attachment) { assertEquals("foo", attachment); writeWithCallback(channel, data, latch); } @Override public void failed(Throwable exc, String attachment) { latch.countDown(); fail("Unexpected failure"); } }); } @Test public void testWriteFuture() throws IOException, InterruptedException, ExecutionException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForWriting(); ByteBuffer writeData = ByteBuffer.wrap(data); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0)) { while (writeData.hasRemaining()) { byte[] buffer = new byte[Math.min(1 + ThreadLocalRandom.current().nextInt(127), writeData.remaining())]; writeData.get(buffer); channel.write(ByteBuffer.wrap(buffer)).get(); } } assertArraysEqual(data, Files.readAllBytes(tempFile)); } @Test public void testWriteWithFutureAndOffset() throws IOException, InterruptedException, ExecutionException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForWriting(); int offset = 117; ByteBuffer expectedData = ByteBuffer.allocate(data.length + offset); expectedData.put(new byte[offset]); expectedData.put(data); expectedData.flip(); ByteBuffer writeData = ByteBuffer.wrap(data); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), offset)) { while (writeData.hasRemaining()) { byte[] buffer = new byte[Math.min(1 + ThreadLocalRandom.current().nextInt(127), writeData.remaining())]; writeData.get(buffer); channel.write(ByteBuffer.wrap(buffer)).get(); } } assertArraysEqual(expectedData.array(), Files.readAllBytes(tempFile)); } @Test public void doesNotAllowConcurrentOperations() { AsynchronousFileChannel fileChannelMock = new MockAsynchronousFileChannel(); ByteBuffer buffer = ByteBuffer.allocate(0); { AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.write(buffer); assertThrows(WritePendingException.class, () -> channel.write(buffer)); assertThrows(WritePendingException.class, () -> channel.write(buffer, null, null)); assertThrows(WritePendingException.class, () -> channel.read(buffer)); assertThrows(WritePendingException.class, () -> channel.read(buffer, null, null)); } { AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.write(buffer, null, null); assertThrows(WritePendingException.class, () -> channel.write(buffer)); assertThrows(WritePendingException.class, () -> channel.write(buffer, null, null)); assertThrows(WritePendingException.class, () -> channel.read(buffer)); assertThrows(WritePendingException.class, () -> channel.read(buffer, null, null)); } { AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.read(buffer); assertThrows(ReadPendingException.class, () -> channel.write(buffer)); assertThrows(ReadPendingException.class, () -> channel.write(buffer, null, null)); assertThrows(ReadPendingException.class, () -> channel.read(buffer)); assertThrows(ReadPendingException.class, () -> channel.read(buffer, null, null)); } { AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.read(buffer, null, null); assertThrows(ReadPendingException.class, () -> channel.write(buffer)); assertThrows(ReadPendingException.class, () -> channel.write(buffer, null, null)); assertThrows(ReadPendingException.class, () -> channel.read(buffer)); assertThrows(ReadPendingException.class, () -> channel.read(buffer, null, null)); } } private Path prepareForReading(byte[] data) throws IOException { Path tempFile = Files.createTempFile("channeladaptertest", null); tempFile.toFile().deleteOnExit(); Files.write(tempFile, data); return tempFile; } private Path prepareForWriting() throws IOException { Path tempFile = Files.createTempFile("channeladaptertest", null); tempFile.toFile().deleteOnExit(); return tempFile; } }
class AsynchronousFileChannelAdapterTest { @Test public void closeDelegates() throws IOException { AtomicInteger closeCalls = new AtomicInteger(); AsynchronousFileChannel fileChannelMock = new MockAsynchronousFileChannel() { @Override public void close() throws IOException { closeCalls.incrementAndGet(); super.close(); } }; AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.close(); assertEquals(1, closeCalls.get()); } @Test public void isOpenDelegates() { AtomicInteger openCalls = new AtomicInteger(); AsynchronousFileChannel fileChannelMock = new MockAsynchronousFileChannel() { @Override public boolean isOpen() { return openCalls.getAndIncrement() == 0; } }; AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); assertTrue(channel.isOpen()); assertFalse(channel.isOpen()); assertEquals(2, openCalls.get()); } @Test public void testReadWithCallback() throws IOException, InterruptedException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForReading(data); ByteBuffer readData = ByteBuffer.allocate(data.length); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.READ), 0)) { CountDownLatch latch = new CountDownLatch(1); readWithCallback(channel, readData, latch); latch.await(60, TimeUnit.SECONDS); } readData.flip(); assertArraysEqual(data, readData.array()); } @Test public void testReadWithCallbackAndOffset() throws IOException, InterruptedException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForReading(data); int offset = 117; ByteBuffer readData = ByteBuffer.allocate(data.length - offset); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.READ), offset)) { CountDownLatch latch = new CountDownLatch(1); readWithCallback(channel, readData, latch); latch.await(60, TimeUnit.SECONDS); } readData.flip(); assertArraysEqual(data, offset, data.length - offset, readData.array(), data.length - offset); } @Test public void testReadWithFuture() throws IOException, InterruptedException, ExecutionException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForReading(data); ByteBuffer readData = ByteBuffer.allocate(data.length); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.READ), 0)) { int read; do { ByteBuffer buffer = ByteBuffer.allocate(1 + ThreadLocalRandom.current().nextInt(127)); read = channel.read(buffer).get(); buffer.flip(); readData.put(buffer); } while (read >= 0); } readData.flip(); assertArraysEqual(data, readData.array()); } @Test public void testReadWithWithFutureAndOffset() throws IOException, InterruptedException, ExecutionException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForReading(data); int offset = 117; ByteBuffer readData = ByteBuffer.allocate(data.length - offset); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.READ), offset)) { int read; do { ByteBuffer buffer = ByteBuffer.allocate(1 + ThreadLocalRandom.current().nextInt(127)); read = channel.read(buffer).get(); buffer.flip(); readData.put(buffer); } while (read >= 0); } readData.flip(); assertArraysEqual(data, offset, data.length - offset, readData.array(), data.length - offset); } @Test public void testWriteWithCallback() throws IOException, InterruptedException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForWriting(); ByteBuffer writeData = ByteBuffer.wrap(data); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0)) { CountDownLatch latch = new CountDownLatch(1); writeWithCallback(channel, writeData, latch); latch.await(60, TimeUnit.SECONDS); } assertArraysEqual(data, Files.readAllBytes(tempFile)); } @Test public void testWriteWithCallbackAndOffset() throws IOException, InterruptedException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForWriting(); int offset = 117; ByteBuffer expectedData = ByteBuffer.allocate(data.length + offset); expectedData.put(new byte[offset]); expectedData.put(data); expectedData.flip(); ByteBuffer writeData = ByteBuffer.wrap(data); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), offset)) { CountDownLatch latch = new CountDownLatch(1); writeWithCallback(channel, writeData, latch); latch.await(60, TimeUnit.SECONDS); } assertArraysEqual(expectedData.array(), Files.readAllBytes(tempFile)); } private static void writeWithCallback(AsynchronousByteChannel channel, ByteBuffer data, CountDownLatch latch) { if (!data.hasRemaining()) { latch.countDown(); return; } byte[] buffer = new byte[Math.min(1 + ThreadLocalRandom.current().nextInt(127), data.remaining())]; data.get(buffer); channel.write(ByteBuffer.wrap(buffer), "foo", new CompletionHandler<Integer, String>() { @Override public void completed(Integer result, String attachment) { assertEquals("foo", attachment); writeWithCallback(channel, data, latch); } @Override public void failed(Throwable exc, String attachment) { latch.countDown(); fail("Unexpected failure"); } }); } @Test public void testWriteFuture() throws IOException, InterruptedException, ExecutionException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForWriting(); ByteBuffer writeData = ByteBuffer.wrap(data); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), 0)) { while (writeData.hasRemaining()) { byte[] buffer = new byte[Math.min(1 + ThreadLocalRandom.current().nextInt(127), writeData.remaining())]; writeData.get(buffer); channel.write(ByteBuffer.wrap(buffer)).get(); } } assertArraysEqual(data, Files.readAllBytes(tempFile)); } @Test public void testWriteWithFutureAndOffset() throws IOException, InterruptedException, ExecutionException { byte[] data = new byte[1024]; fillArray(data); Path tempFile = prepareForWriting(); int offset = 117; ByteBuffer expectedData = ByteBuffer.allocate(data.length + offset); expectedData.put(new byte[offset]); expectedData.put(data); expectedData.flip(); ByteBuffer writeData = ByteBuffer.wrap(data); try (AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter( AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE), offset)) { while (writeData.hasRemaining()) { byte[] buffer = new byte[Math.min(1 + ThreadLocalRandom.current().nextInt(127), writeData.remaining())]; writeData.get(buffer); channel.write(ByteBuffer.wrap(buffer)).get(); } } assertArraysEqual(expectedData.array(), Files.readAllBytes(tempFile)); } @Test public void doesNotAllowConcurrentOperations() { AsynchronousFileChannel fileChannelMock = new MockAsynchronousFileChannel(); ByteBuffer buffer = ByteBuffer.allocate(0); { AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.write(buffer); assertThrows(WritePendingException.class, () -> channel.write(buffer)); assertThrows(WritePendingException.class, () -> channel.write(buffer, null, null)); assertThrows(WritePendingException.class, () -> channel.read(buffer)); assertThrows(WritePendingException.class, () -> channel.read(buffer, null, null)); } { AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.write(buffer, null, null); assertThrows(WritePendingException.class, () -> channel.write(buffer)); assertThrows(WritePendingException.class, () -> channel.write(buffer, null, null)); assertThrows(WritePendingException.class, () -> channel.read(buffer)); assertThrows(WritePendingException.class, () -> channel.read(buffer, null, null)); } { AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.read(buffer); assertThrows(ReadPendingException.class, () -> channel.write(buffer)); assertThrows(ReadPendingException.class, () -> channel.write(buffer, null, null)); assertThrows(ReadPendingException.class, () -> channel.read(buffer)); assertThrows(ReadPendingException.class, () -> channel.read(buffer, null, null)); } { AsynchronousByteChannel channel = new AsynchronousFileChannelAdapter(fileChannelMock, 0); channel.read(buffer, null, null); assertThrows(ReadPendingException.class, () -> channel.write(buffer)); assertThrows(ReadPendingException.class, () -> channel.write(buffer, null, null)); assertThrows(ReadPendingException.class, () -> channel.read(buffer)); assertThrows(ReadPendingException.class, () -> channel.read(buffer, null, null)); } } private Path prepareForReading(byte[] data) throws IOException { Path tempFile = Files.createTempFile("channeladaptertest", null); tempFile.toFile().deleteOnExit(); Files.write(tempFile, data); return tempFile; } private Path prepareForWriting() throws IOException { Path tempFile = Files.createTempFile("channeladaptertest", null); tempFile.toFile().deleteOnExit(); return tempFile; } }
I'm not clear on our naming patterns in this library but is `isOverwrite` and `isOverwriteMode()` the correct name combo? The getter makes sense to me, but I would imagine the constructor parameter name would then be `overwrite` or `overwriteMode`, as if it were a parameter in a setter called `setOverwriteMode(boolean overwriteMode)`. @alzimmermsft am I missing the mark here?
public boolean isOverwriteMode() { return isOverwrite; }
return isOverwrite;
public boolean isOverwriteMode() { return overwriteMode; }
class ShareFileSeekableByteChannelWriteOptions { private static final ClientLogger LOGGER = new ClientLogger(ShareFileSeekableByteChannelWriteOptions.class); private final boolean isOverwrite; private Long fileSize; private ShareRequestConditions requestConditions; private FileLastWrittenMode fileLastWrittenMode; private Long chunkSizeInBytes; /** * Options constructor. * @param isOverwrite Whether to open the channel in write mode. */ public ShareFileSeekableByteChannelWriteOptions(boolean isOverwrite) { this.isOverwrite = isOverwrite; } /** * @return Whether the channel is in write mode. */ /** * This parameter is required when opening the channel to write. * @return New size of the target file. */ public Long getFileSizeInBytes() { return fileSize; } /** * @param fileSize New size of the target file. * @return The updated instance. * @throws UnsupportedOperationException When setting a file size on options that don't create a new file. */ public ShareFileSeekableByteChannelWriteOptions setFileSize(Long fileSize) { if (!isOverwrite) { throw LOGGER.logExceptionAsError( new UnsupportedOperationException("Cannot set 'fileSize' unless creating a new file.")); } if (fileSize != null && fileSize < 0) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fileSize' must be a non-negative number if provided.")); } this.fileSize = fileSize; return this; } /** * @return The size of individual writes to the service. */ public Long getChunkSizeInBytes() { return chunkSizeInBytes; } /** * @param chunkSizeInBytes The size of individual writes to the service. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setChunkSizeInBytes(Long chunkSizeInBytes) { this.chunkSizeInBytes = chunkSizeInBytes; return this; } /** * @return Request conditions to be used by the resulting channel. */ public ShareRequestConditions getRequestConditions() { return requestConditions; } /** * @param requestConditions Request conditions to be used by the resulting channel. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setRequestConditions(ShareRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return The last wriiten mode to be used by the resulting channel. */ public FileLastWrittenMode getFileLastWrittenMode() { return fileLastWrittenMode; } /** * @param fileLastWrittenMode The last wriiten mode to be used by the resulting channel. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setFileLastWrittenMode(FileLastWrittenMode fileLastWrittenMode) { this.fileLastWrittenMode = fileLastWrittenMode; return this; } }
class ShareFileSeekableByteChannelWriteOptions { private static final ClientLogger LOGGER = new ClientLogger(ShareFileSeekableByteChannelWriteOptions.class); private final boolean overwriteMode; private Long fileSize; private ShareRequestConditions requestConditions; private FileLastWrittenMode fileLastWrittenMode; private Long chunkSizeInBytes; /** * Options constructor. * @param overwriteMode If {@code true}, the channel will be opened in overwrite mode. Otherwise, the channel will * be opened in write mode. */ public ShareFileSeekableByteChannelWriteOptions(boolean overwriteMode) { this.overwriteMode = overwriteMode; } /** * @return Whether the channel is in write mode. */ /** * This parameter is required when opening the channel to write. * @return New size of the target file. */ public Long getFileSizeInBytes() { return fileSize; } /** * @param fileSize New size of the target file. * @return The updated instance. * @throws UnsupportedOperationException When setting a file size on options that don't create a new file. */ public ShareFileSeekableByteChannelWriteOptions setFileSize(Long fileSize) { if (!overwriteMode) { throw LOGGER.logExceptionAsError( new UnsupportedOperationException("Cannot set 'fileSize' unless creating a new file.")); } if (fileSize != null && fileSize < 0) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fileSize' must be a non-negative number if provided.")); } this.fileSize = fileSize; return this; } /** * @return The size of individual writes to the service. */ public Long getChunkSizeInBytes() { return chunkSizeInBytes; } /** * @param chunkSizeInBytes The size of individual writes to the service. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setChunkSizeInBytes(Long chunkSizeInBytes) { this.chunkSizeInBytes = chunkSizeInBytes; return this; } /** * @return Request conditions to be used by the resulting channel. */ public ShareRequestConditions getRequestConditions() { return requestConditions; } /** * @param requestConditions Request conditions to be used by the resulting channel. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setRequestConditions(ShareRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return The last wriiten mode to be used by the resulting channel. */ public FileLastWrittenMode getFileLastWrittenMode() { return fileLastWrittenMode; } /** * @param fileLastWrittenMode The last wriiten mode to be used by the resulting channel. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setFileLastWrittenMode(FileLastWrittenMode fileLastWrittenMode) { this.fileLastWrittenMode = fileLastWrittenMode; return this; } }
Given Java doesn't have named parameters the naming in the constructor isn't as important, but I agree with the assessment that using `overwriteMode` would have the best reading flow. And I also agree with the setter method naming.
public boolean isOverwriteMode() { return isOverwrite; }
return isOverwrite;
public boolean isOverwriteMode() { return overwriteMode; }
class ShareFileSeekableByteChannelWriteOptions { private static final ClientLogger LOGGER = new ClientLogger(ShareFileSeekableByteChannelWriteOptions.class); private final boolean isOverwrite; private Long fileSize; private ShareRequestConditions requestConditions; private FileLastWrittenMode fileLastWrittenMode; private Long chunkSizeInBytes; /** * Options constructor. * @param isOverwrite Whether to open the channel in write mode. */ public ShareFileSeekableByteChannelWriteOptions(boolean isOverwrite) { this.isOverwrite = isOverwrite; } /** * @return Whether the channel is in write mode. */ /** * This parameter is required when opening the channel to write. * @return New size of the target file. */ public Long getFileSizeInBytes() { return fileSize; } /** * @param fileSize New size of the target file. * @return The updated instance. * @throws UnsupportedOperationException When setting a file size on options that don't create a new file. */ public ShareFileSeekableByteChannelWriteOptions setFileSize(Long fileSize) { if (!isOverwrite) { throw LOGGER.logExceptionAsError( new UnsupportedOperationException("Cannot set 'fileSize' unless creating a new file.")); } if (fileSize != null && fileSize < 0) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fileSize' must be a non-negative number if provided.")); } this.fileSize = fileSize; return this; } /** * @return The size of individual writes to the service. */ public Long getChunkSizeInBytes() { return chunkSizeInBytes; } /** * @param chunkSizeInBytes The size of individual writes to the service. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setChunkSizeInBytes(Long chunkSizeInBytes) { this.chunkSizeInBytes = chunkSizeInBytes; return this; } /** * @return Request conditions to be used by the resulting channel. */ public ShareRequestConditions getRequestConditions() { return requestConditions; } /** * @param requestConditions Request conditions to be used by the resulting channel. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setRequestConditions(ShareRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return The last wriiten mode to be used by the resulting channel. */ public FileLastWrittenMode getFileLastWrittenMode() { return fileLastWrittenMode; } /** * @param fileLastWrittenMode The last wriiten mode to be used by the resulting channel. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setFileLastWrittenMode(FileLastWrittenMode fileLastWrittenMode) { this.fileLastWrittenMode = fileLastWrittenMode; return this; } }
class ShareFileSeekableByteChannelWriteOptions { private static final ClientLogger LOGGER = new ClientLogger(ShareFileSeekableByteChannelWriteOptions.class); private final boolean overwriteMode; private Long fileSize; private ShareRequestConditions requestConditions; private FileLastWrittenMode fileLastWrittenMode; private Long chunkSizeInBytes; /** * Options constructor. * @param overwriteMode If {@code true}, the channel will be opened in overwrite mode. Otherwise, the channel will * be opened in write mode. */ public ShareFileSeekableByteChannelWriteOptions(boolean overwriteMode) { this.overwriteMode = overwriteMode; } /** * @return Whether the channel is in write mode. */ /** * This parameter is required when opening the channel to write. * @return New size of the target file. */ public Long getFileSizeInBytes() { return fileSize; } /** * @param fileSize New size of the target file. * @return The updated instance. * @throws UnsupportedOperationException When setting a file size on options that don't create a new file. */ public ShareFileSeekableByteChannelWriteOptions setFileSize(Long fileSize) { if (!overwriteMode) { throw LOGGER.logExceptionAsError( new UnsupportedOperationException("Cannot set 'fileSize' unless creating a new file.")); } if (fileSize != null && fileSize < 0) { throw LOGGER.logExceptionAsError( new IllegalArgumentException("'fileSize' must be a non-negative number if provided.")); } this.fileSize = fileSize; return this; } /** * @return The size of individual writes to the service. */ public Long getChunkSizeInBytes() { return chunkSizeInBytes; } /** * @param chunkSizeInBytes The size of individual writes to the service. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setChunkSizeInBytes(Long chunkSizeInBytes) { this.chunkSizeInBytes = chunkSizeInBytes; return this; } /** * @return Request conditions to be used by the resulting channel. */ public ShareRequestConditions getRequestConditions() { return requestConditions; } /** * @param requestConditions Request conditions to be used by the resulting channel. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setRequestConditions(ShareRequestConditions requestConditions) { this.requestConditions = requestConditions; return this; } /** * @return The last wriiten mode to be used by the resulting channel. */ public FileLastWrittenMode getFileLastWrittenMode() { return fileLastWrittenMode; } /** * @param fileLastWrittenMode The last wriiten mode to be used by the resulting channel. * @return The updated instance. */ public ShareFileSeekableByteChannelWriteOptions setFileLastWrittenMode(FileLastWrittenMode fileLastWrittenMode) { this.fileLastWrittenMode = fileLastWrittenMode; return this; } }
Was this required for all or just one of the tests?
static void beforeAll() throws InterruptedException { TimeUnit.SECONDS.sleep(180); StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); }
TimeUnit.SECONDS.sleep(180);
static void beforeAll() throws InterruptedException { TimeUnit.SECONDS.sleep(180); StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } private TextAnalyticsAsyncClient getTextAnalyticsAsyncClient(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion, boolean isStaticResource) { return getTextAnalyticsClientBuilder( buildAsyncAssertingClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), serviceVersion, isStaticResource) .buildAsyncClient(); } /** * Verify that we can get statistics on the collection result when given a batch of documents with request options. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageShowStatisticsRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, options)) .assertNext(response -> validateDetectLanguageResultCollectionWithResponse(true, getExpectedBatchDetectedLanguages(), 200, response)) .verifyComplete()); } /** * Test to detect language for each {@code DetectLanguageResult} input of a batch. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageRunner((inputs) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, null)) .assertNext(response -> validateDetectLanguageResultCollectionWithResponse(false, getExpectedBatchDetectedLanguages(), 200, response)) .verifyComplete()); } /** * Test to detect language for each string input of batch with given country hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchListCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguagesCountryHintRunner((inputs, countryHint) -> StepVerifier.create(client.detectLanguageBatch(inputs, countryHint, null)) .assertNext(actualResults -> validateDetectLanguageResultCollection(false, getExpectedBatchDetectedLanguages(), actualResults)) .verifyComplete()); } /** * Test to detect language for each string input of batch with request options. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchListCountryHintWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguagesBatchListCountryHintWithOptionsRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatch(inputs, null, options)) .assertNext(response -> validateDetectLanguageResultCollection(true, getExpectedBatchDetectedLanguages(), response)) .verifyComplete()); } /** * Test to detect language for each string input of batch. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageStringInputRunner((inputs) -> StepVerifier.create(client.detectLanguageBatch(inputs, null, null)) .assertNext(response -> validateDetectLanguageResultCollection(false, getExpectedBatchDetectedLanguages(), response)) .verifyComplete()); } /** * Verifies that a single DetectedLanguage is returned for a document to detectLanguage. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectSingleTextLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectSingleTextLanguageRunner(input -> StepVerifier.create(client.detectLanguage(input)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageEnglish(), response)) .verifyComplete()); } /** * Verifies that an TextAnalyticsException is thrown for a document with invalid country hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageInvalidCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageInvalidCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_COUNTRY_HINT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that TextAnalyticsException is thrown for an empty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.detectLanguage(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that a bad request exception is returned for input documents with same ids. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageDuplicateIdRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, options)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } /** * Verifies that an invalid document exception is returned for input documents with an empty ID. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageInputEmptyIdRunner(inputs -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } /** * Verify that with countryHint with empty string will not throw exception. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageEmptyCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageSpanish(), response)) .verifyComplete()); } /** * Verify that with countryHint with "none" will not throw exception. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageNoneCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageNoneCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageSpanish(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntitiesForSingleTextInputRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .assertNext(response -> validateCategorizedEntities(response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntitySingleErrorRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .assertNext(resultCollection -> resultCollection.getValue().forEach(recognizeEntitiesResult -> { Exception exception = assertThrows(TextAnalyticsException.class, recognizeEntitiesResult::getEntities); assertEquals(String.format(BATCH_ERROR_EXCEPTION_MESSAGE, "RecognizeEntitiesResult"), exception.getMessage()); })).verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntityRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validateCategorizedEntitiesResultCollectionWithResponse(false, getExpectedBatchCategorizedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validateCategorizedEntitiesResultCollectionWithResponse(true, getExpectedBatchCategorizedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntityStringInputRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, null)) .assertNext(response -> validateCategorizedEntitiesResultCollection(false, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntitiesLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, language, null)) .assertNext(response -> validateCategorizedEntitiesResultCollection(false, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForListWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchCategorizedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, options)) .assertNext(response -> validateCategorizedEntitiesResultCollection(true, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void recognizeEntitiesBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(15, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(22, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(30, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(14, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(15, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(126, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesResolutions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeEntitiesBatchResolutionRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, options)) .assertNext(recognizeEntitiesResults -> validateEntityResolutions(recognizeEntitiesResults)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiSingleDocumentRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(response -> validatePiiEntities(getPiiEntitiesList1(), response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitySingleErrorRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .assertNext(resultCollection -> resultCollection.getValue().forEach(recognizePiiEntitiesResult -> { Exception exception = assertThrows(TextAnalyticsException.class, recognizePiiEntitiesResult::getEntities); assertEquals(String.format(BATCH_ERROR_EXCEPTION_MESSAGE, "RecognizePiiEntitiesResult"), exception.getMessage()); })).verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(false, getExpectedBatchPiiEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(true, getExpectedBatchPiiEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, language, null)) .assertNext(response -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, null, options)) .assertNext(response -> validatePiiEntitiesResultCollection(true, getExpectedBatchPiiEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(10, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(17, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(25, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(9, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(10, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(121, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiDomainFilterRunner((document, options) -> StepVerifier.create(client.recognizePiiEntities(document, "en", options)) .assertNext(response -> validatePiiEntities(getPiiEntitiesList1ForDomainFilter(), response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputStringForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, language, new RecognizePiiEntitiesOptions().setDomainFilter(PiiEntityDomain.PROTECTED_HEALTH_INFORMATION))) .assertNext(response -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForDomainFilter(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, new RecognizePiiEntitiesOptions().setDomainFilter(PiiEntityDomain.PROTECTED_HEALTH_INFORMATION))) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(false, getExpectedBatchPiiEntitiesForDomainFilter(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputForCategoriesFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesForCategoriesFilterRunner( (inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntityWithCategoriesFilterFromOtherResult(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesForCategoriesFilterRunner( (inputs, options) -> { List<PiiEntityCategory> categories = new ArrayList<>(); StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> { resultCollection.forEach(result -> result.getEntities().forEach(piiEntity -> { final PiiEntityCategory category = piiEntity.getCategory(); if (PiiEntityCategory.ABA_ROUTING_NUMBER == category || PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER == category) { categories.add(category); } })); validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection); }) .verifyComplete(); final PiiEntityCategory[] piiEntityCategories = categories.toArray(new PiiEntityCategory[categories.size()]); options.setCategoriesFilter(piiEntityCategories); StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedEntitiesForSingleTextInputRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .assertNext(response -> validateLinkedEntity(getLinkedEntitiesList1().get(0), response.iterator().next())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchLinkedEntityRunner((inputs) -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validateLinkedEntitiesResultCollectionWithResponse(false, getExpectedBatchLinkedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchLinkedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validateLinkedEntitiesResultCollectionWithResponse(true, getExpectedBatchLinkedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedStringInputRunner((inputs) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, null)) .assertNext(response -> validateLinkedEntitiesResultCollection(false, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, language, null)) .assertNext(response -> validateLinkedEntitiesResultCollection(false, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchStringLinkedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, options)) .assertNext(response -> validateLinkedEntitiesResultCollection(true, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(15, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(22, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(30, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(14, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(15, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(126, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesForSingleTextInputRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesCollection -> validateKeyPhrases(asList("monde"), keyPhrasesCollection.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchKeyPhrasesRunner((inputs) -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollectionWithResponse(false, getExpectedBatchKeyPhrases(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchKeyPhrasesShowStatsRunner((inputs, options) -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, options)) .assertNext(response -> validateExtractKeyPhrasesResultCollectionWithResponse(true, getExpectedBatchKeyPhrases(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesStringInputRunner((inputs) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(false, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesLanguageHintRunner((inputs, language) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, language, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(false, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchStringKeyPhrasesShowStatsRunner((inputs, options) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, options)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(true, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesWarningRunner( input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesResult -> { keyPhrasesResult.getWarnings().forEach(warning -> { assertTrue(WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE.equals(warning.getMessage())); assertTrue(LONG_WORDS_IN_DOCUMENT.equals(warning.getWarningCode())); }); }) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesBatchWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesBatchWarningRunner( inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .assertNext(response -> response.getValue().forEach(keyPhrasesResult -> keyPhrasesResult.getKeyPhrases().getWarnings().forEach(warning -> { assertTrue(WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE.equals(warning.getMessage())); assertTrue(LONG_WORDS_IN_DOCUMENT.equals(warning.getWarningCode())); }) )) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } /** * Test analyzing sentiment for a string input. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForSingleTextInputRunner(input -> StepVerifier.create(client.analyzeSentiment(input)) .assertNext(response -> validateDocumentSentiment(false, getExpectedDocumentSentiment(), response)) .verifyComplete() ); } /** * Test analyzing sentiment for a string input with default language hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInputWithDefaultLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForSingleTextInputRunner(input -> StepVerifier.create(client.analyzeSentiment(input, null)) .assertNext(response -> validateDocumentSentiment(false, getExpectedDocumentSentiment(), response)) .verifyComplete() ); } /** * Test analyzing sentiment for a string input and verifying the result of opinion mining. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInputWithOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForTextInputWithOpinionMiningRunner((input, options) -> StepVerifier.create(client.analyzeSentiment(input, "en", options)) .assertNext(response -> validateDocumentSentiment(true, getExpectedDocumentSentiment(), response)) .verifyComplete()); } /** * Verifies that an TextAnalyticsException is thrown for an empty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(document -> StepVerifier.create(client.analyzeSentiment(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } /** * Test analyzing sentiment for a duplicate ID list. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, new TextAnalyticsRequestOptions())) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } /** * Verifies that an invalid document exception is returned for input documents with an empty ID. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * String documents with null TextAnalyticsRequestOptions and null language code which will use the default language * code, 'en'. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null and null language code which will use the default language code, 'en'. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentStringInputRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, new TextAnalyticsRequestOptions())) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * String documents with null TextAnalyticsRequestOptions and given a language code. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null and given a language code. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringWithLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentLanguageHintRunner((inputs, language) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, language, new TextAnalyticsRequestOptions())) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result includes request statistics but not sentence options when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which to show the request statistics only and verify the analyzed sentiment result. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringShowStatisticsExcludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options.setIncludeOpinionMining(false))) .assertNext(response -> validateAnalyzeSentimentResultCollection(true, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result includes sentence options but not request statistics when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringNotShowStatisticsButIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> { options.setIncludeStatistics(false); StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options)) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, true, getExpectedBatchTextSentiment(), response)) .verifyComplete(); }); } /** * Verify that the collection result includes sentence options and request statistics when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringShowStatisticsAndIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options)) .assertNext(response -> validateAnalyzeSentimentResultCollection(true, true, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * TextDocumentInput documents with null TextAnalyticsRequestOptions. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputWithNullRequestOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, (TextAnalyticsRequestOptions) null)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that we can get statistics on the collection result when given a batch of * TextDocumentInput documents with TextAnalyticsRequestOptions. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions includes request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentShowStatsRunner((inputs, requestOptions) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, requestOptions)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * TextDocumentInput documents with null AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions is null. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputWithNullAnalyzeSentimentOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, (AnalyzeSentimentOptions) null)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result includes request statistics but not sentence options when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes request statistics but not opinion mining. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatisticsExcludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options.setIncludeOpinionMining(false))) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result includes sentence options but not request statistics when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining but not request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputNotShowStatisticsButIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> { options.setIncludeStatistics(false); StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, true, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete(); }); } /** * Verify that the collection result includes sentence options and request statistics when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatisticsAndIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, true, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verifies that an InvalidDocumentBatch exception is returned for input documents with too many documents. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(opinionSentiment -> { assertEquals(7, opinionSentiment.getLength()); assertEquals(17, opinionSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(27, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(19, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(9, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext( result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(34, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(26, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(16, targetSentiment.getOffset()); }); }) ) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext( result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(42, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(34, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(24, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(26, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(18, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(8, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(27, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(19, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(9, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(17, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(17, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(138, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(130, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(120, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareStringInputWithoutOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareStringInputRunner((documents, dummyOptions) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( false, getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareStringInputWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareStringInputRunner((documents, options) -> { boolean isValidApiVersionForDisplayName = serviceVersion != TextAnalyticsServiceVersion.V3_0 && serviceVersion != TextAnalyticsServiceVersion.V3_1; if (isValidApiVersionForDisplayName) { options.setDisplayName("operationName"); } SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<AnalyzeHealthcareEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); if (isValidApiVersionForDisplayName) { assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); } AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePageWithFhir(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareMaxOverload(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareLroRunner((documents, options) -> { boolean isValidApiVersionForDisplayName = serviceVersion != TextAnalyticsServiceVersion.V3_0 && serviceVersion != TextAnalyticsServiceVersion.V3_1; if (isValidApiVersionForDisplayName) { options.setDisplayName("operationName"); } SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<AnalyzeHealthcareEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); if (isValidApiVersionForDisplayName) { assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); } AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareLroPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareLroPaginationRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForMultiplePages(0, 10, 0), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }, 10); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareLroEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyListRunner((documents, errorMessage) -> { StepVerifier.create(client.beginAnalyzeHealthcareEntities(documents, null)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && errorMessage.equals(throwable.getMessage())) .verify(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void analyzeHealthcareEntitiesEmojiUnicodeCodePoint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(22, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(29, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(37, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(21, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(22, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(133, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesForAssertion(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeHealthcareEntitiesForAssertionRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); final HealthcareEntityAssertion assertion = analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList()) .get(0).stream().collect(Collectors.toList()) .get(0).getEntities().stream().collect(Collectors.toList()) .get(1) .getAssertion(); assertEquals(EntityConditionality.HYPOTHETICAL, assertion.getConditionality()); assertNull(assertion.getAssociation()); assertNull(assertion.getCertainty()); }); } @Disabled("Temporary disable it for green test") @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void cancelHealthcareLro(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); cancelHealthcareLroRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.cancelOperation(); LongRunningOperationStatus operationStatus = syncPoller.poll().getStatus(); while (!LongRunningOperationStatus.USER_CANCELLED.equals(operationStatus)) { operationStatus = syncPoller.poll().getStatus(); } syncPoller.waitForCompletion(); Assertions.assertEquals(LongRunningOperationStatus.USER_CANCELLED, operationStatus); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsStringInputRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForActions(), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getRecognizePiiEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchActionsRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForActions(), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getRecognizePiiEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithMultiSameKindActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsWithMultiSameKindActionsRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { assertEquals(2, actionsResult.getRecognizeEntitiesResults().stream().count()); assertEquals(2, actionsResult.getRecognizePiiEntitiesResults().stream().count()); assertEquals(2, actionsResult.getRecognizeLinkedEntitiesResults().stream().count()); assertEquals(2, actionsResult.getAnalyzeSentimentResults().stream().count()); assertEquals(2, actionsResult.getExtractKeyPhrasesResults().stream().count()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithActionNames(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsWithActionNamesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizeEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizePiiEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizeLinkedEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getAnalyzeSentimentResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getExtractKeyPhrasesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsAutoDetectedLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsAutoDetectedLanguageRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { List<RecognizeEntitiesResult> recognizeEntitiesResults = actionsResult.getRecognizeEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizeEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizeEntitiesResults.get(1).getDetectedLanguage()); List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = actionsResult.getRecognizePiiEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizePiiEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizePiiEntitiesResults.get(1).getDetectedLanguage()); List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResults = actionsResult.getRecognizeLinkedEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizeLinkedEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizeLinkedEntitiesResults.get(1).getDetectedLanguage()); List<AnalyzeSentimentResult> analyzeSentimentResults = actionsResult.getAnalyzeSentimentResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, analyzeSentimentResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, analyzeSentimentResults.get(1).getDetectedLanguage()); List<ExtractKeyPhraseResult> keyPhraseResults = actionsResult.getExtractKeyPhrasesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, keyPhraseResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, keyPhraseResults.get(1).getDetectedLanguage()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsAutoDetectedLanguageCustomTexts(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); analyzeActionsAutoDetectedLanguageCustomTextRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { List<RecognizeEntitiesResult> customEntitiesResults = actionsResult.getRecognizeCustomEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, customEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, customEntitiesResults.get(1).getDetectedLanguage()); List<ClassifyDocumentResult> singleLabelResults = actionsResult.getSingleLabelClassifyResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, singleLabelResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, singleLabelResults.get(1).getDetectedLanguage()); List<ClassifyDocumentResult> multiLabelResults = actionsResult.getMultiLabelClassifyResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, multiLabelResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, multiLabelResults.get(1).getDetectedLanguage()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchActionsPaginationRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions( documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, getExpectedAnalyzeActionsResultListForMultiplePages(0, 20, 2), result.toStream().collect(Collectors.toList())); }, 22); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyListRunner((documents, errorMessage) -> StepVerifier.create(client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setRecognizeEntitiesActions(new RecognizeEntitiesAction()), null)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && errorMessage.equals(throwable.getMessage())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeEntitiesRecognitionAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeEntitiesRecognitionRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeEntitiesRecognitionActionResolution(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeEntitiesRecognitionResolutionRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().forEach(actionsResult -> { actionsResult.getRecognizeEntitiesResults().forEach(nerActionResult -> { validateEntityResolutions(nerActionResult.getDocumentsResults()); }); }); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithCategoriesFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzePiiEntityRecognitionWithCategoriesFiltersRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForCategoriesFilter(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithDomainFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzePiiEntityRecognitionWithDomainFiltersRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForDomainFilter(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeLinkedEntityActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeLinkedEntityRecognitionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList( false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeKeyPhrasesExtractionAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getExpectedBatchTextSentiment(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeHealthcareEntitiesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedAnalyzeHealthcareEntitiesActionResult(false, null, TIME_NOW, getExpectedAnalyzeHealthcareEntitiesResultCollection(2, asList( getRecognizeHealthcareEntitiesResultWithFhir1("0"), getRecognizeHealthcareEntitiesResultWithFhir2())), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntitiesAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getRecognizeCustomEntitiesResults().forEach( customEntitiesActionResult -> customEntitiesActionResult.getDocumentsResults().forEach( documentResult -> validateCategorizedEntities( documentResult.getEntities().stream().collect(Collectors.toList()))))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassificationAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleCategoryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getSingleLabelClassifyResults().forEach( customSingleCategoryActionResult -> customSingleCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateLabelClassificationResult(documentResult)))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiCategoryClassifyAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiCategoryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getMultiLabelClassifyResults().forEach( customMultiCategoryActionResult -> customMultiCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateLabelClassificationResult(documentResult)))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntitiesStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesRunner((documents, parameters) -> { SyncPoller<RecognizeCustomEntitiesOperationDetail, RecognizeCustomEntitiesPagedFlux> syncPoller = client.beginRecognizeCustomEntities(documents, parameters.get(0), parameters.get(1)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); RecognizeCustomEntitiesPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateCategorizedEntities(documentResult.getEntities().stream().collect(Collectors.toList())))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntities(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesRunner((documents, parameters) -> { RecognizeCustomEntitiesOptions options = new RecognizeCustomEntitiesOptions() .setDisplayName("operationName"); SyncPoller<RecognizeCustomEntitiesOperationDetail, RecognizeCustomEntitiesPagedFlux> syncPoller = client.beginRecognizeCustomEntities(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<RecognizeCustomEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); RecognizeCustomEntitiesPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateCategorizedEntities(documentResult.getEntities().stream().collect(Collectors.toList())))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassificationStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleLabelRunner((documents, parameters) -> { SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginSingleLabelClassify(documents, parameters.get(0), parameters.get(1)) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassification(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleLabelRunner((documents, parameters) -> { SingleLabelClassifyOptions options = new SingleLabelClassifyOptions().setDisplayName("operationName"); SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginSingleLabelClassify(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<ClassifyDocumentOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiLabelClassificationStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiLabelRunner((documents, parameters) -> { SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginMultiLabelClassify(documents, parameters.get(0), parameters.get(1)) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiLabelClassification(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiLabelRunner((documents, parameters) -> { MultiLabelClassifyOptions options = new MultiLabelClassifyOptions().setDisplayName("operationName"); SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginMultiLabelClassify(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<ClassifyDocumentOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExtractSummaryActionResult(false, null, TIME_NOW, getExpectedExtractSummaryResultCollection(getExpectedExtractSummaryResultSortByOffset()), null))), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }, null, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionSortedByOffset(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue(isAscendingOrderByOffSet( documentResult.getSentences().stream().collect(Collectors.toList())))))); }, 4, SummarySentencesOrder.OFFSET); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionSortedByRankScore(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue(isDescendingOrderByRankScore( documentResult.getSentences().stream().collect(Collectors.toList())))))); }, 4, SummarySentencesOrder.RANK); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithSentenceCountLessThanMaxCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue( documentResult.getSentences().stream().collect(Collectors.toList()).size() < 20)))); }, 20, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithNonDefaultSentenceCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertEquals( documentResult.getSentences().stream().collect(Collectors.toList()).size(), 5)))); }, 5, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionMaxSentenceCountInvalidRangeException(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { extractSummaryActionRunner( (documents, tasks) -> { HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); }); assertEquals( TextAnalyticsErrorCode.INVALID_PARAMETER_VALUE, ((TextAnalyticsError) exception.getValue()).getErrorCode()); }, invalidCount, null); } } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeAbstractiveSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getAbstractSummaryActionResult(false, null, TIME_NOW, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), null ))) )), result.toStream().collect(Collectors.toList())); }, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryRunner((documents, options) -> { SyncPoller<AbstractSummaryOperationDetail, AbstractSummaryPagedFlux> syncPoller = client.beginAbstractSummary(documents) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AbstractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResult -> validateAbstractiveSummaryResultCollection(false, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), documentResult)); }, 4); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryMaxOverload(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryMaxOverloadRunner((documents, options) -> { SyncPoller<AbstractSummaryOperationDetail, AbstractSummaryPagedFlux> syncPoller = client.beginAbstractSummary(documents, options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AbstractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResult -> validateAbstractiveSummaryResultCollection(false, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), documentResult)); }, 4); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySortedByOffset(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( isAscendingOrderByOffSet(documentResult.getSentences().stream().collect(Collectors.toList()))) )); }, 4, SummarySentencesOrder.OFFSET); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySortedByRankScore(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( isDescendingOrderByRankScore(documentResult.getSentences().stream().collect(Collectors.toList()))) )); }, 4, SummarySentencesOrder.RANK); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySentenceCountLessThanMaxCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( documentResult.getSentences().stream().collect(Collectors.toList()).size() < 20))); }, 20, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummaryNonDefaultSentenceCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertEquals( documentResult.getSentences().stream().collect(Collectors.toList()).size(), 5))); }, 5, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummaryMaxSentenceCountInvalidRangeException(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { extractSummaryRunner( (documents, options) -> { HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); }); assertEquals( TextAnalyticsErrorCode.INVALID_PARAMETER_VALUE, ((TextAnalyticsError) exception.getValue()).getErrorCode()); }, invalidCount, null); } } }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } private TextAnalyticsAsyncClient getTextAnalyticsAsyncClient(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion, boolean isStaticResource) { return getTextAnalyticsClientBuilder( buildAsyncAssertingClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), serviceVersion, isStaticResource) .buildAsyncClient(); } /** * Verify that we can get statistics on the collection result when given a batch of documents with request options. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageShowStatisticsRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, options)) .assertNext(response -> validateDetectLanguageResultCollectionWithResponse(true, getExpectedBatchDetectedLanguages(), 200, response)) .verifyComplete()); } /** * Test to detect language for each {@code DetectLanguageResult} input of a batch. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageRunner((inputs) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, null)) .assertNext(response -> validateDetectLanguageResultCollectionWithResponse(false, getExpectedBatchDetectedLanguages(), 200, response)) .verifyComplete()); } /** * Test to detect language for each string input of batch with given country hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchListCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguagesCountryHintRunner((inputs, countryHint) -> StepVerifier.create(client.detectLanguageBatch(inputs, countryHint, null)) .assertNext(actualResults -> validateDetectLanguageResultCollection(false, getExpectedBatchDetectedLanguages(), actualResults)) .verifyComplete()); } /** * Test to detect language for each string input of batch with request options. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchListCountryHintWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguagesBatchListCountryHintWithOptionsRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatch(inputs, null, options)) .assertNext(response -> validateDetectLanguageResultCollection(true, getExpectedBatchDetectedLanguages(), response)) .verifyComplete()); } /** * Test to detect language for each string input of batch. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageStringInputRunner((inputs) -> StepVerifier.create(client.detectLanguageBatch(inputs, null, null)) .assertNext(response -> validateDetectLanguageResultCollection(false, getExpectedBatchDetectedLanguages(), response)) .verifyComplete()); } /** * Verifies that a single DetectedLanguage is returned for a document to detectLanguage. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectSingleTextLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectSingleTextLanguageRunner(input -> StepVerifier.create(client.detectLanguage(input)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageEnglish(), response)) .verifyComplete()); } /** * Verifies that an TextAnalyticsException is thrown for a document with invalid country hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageInvalidCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageInvalidCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_COUNTRY_HINT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that TextAnalyticsException is thrown for an empty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.detectLanguage(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that a bad request exception is returned for input documents with same ids. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageDuplicateIdRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, options)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } /** * Verifies that an invalid document exception is returned for input documents with an empty ID. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageInputEmptyIdRunner(inputs -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } /** * Verify that with countryHint with empty string will not throw exception. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageEmptyCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageSpanish(), response)) .verifyComplete()); } /** * Verify that with countryHint with "none" will not throw exception. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageNoneCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageNoneCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageSpanish(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntitiesForSingleTextInputRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .assertNext(response -> validateCategorizedEntities(response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntitySingleErrorRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .assertNext(resultCollection -> resultCollection.getValue().forEach(recognizeEntitiesResult -> { Exception exception = assertThrows(TextAnalyticsException.class, recognizeEntitiesResult::getEntities); assertEquals(String.format(BATCH_ERROR_EXCEPTION_MESSAGE, "RecognizeEntitiesResult"), exception.getMessage()); })).verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntityRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validateCategorizedEntitiesResultCollectionWithResponse(false, getExpectedBatchCategorizedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validateCategorizedEntitiesResultCollectionWithResponse(true, getExpectedBatchCategorizedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntityStringInputRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, null)) .assertNext(response -> validateCategorizedEntitiesResultCollection(false, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntitiesLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, language, null)) .assertNext(response -> validateCategorizedEntitiesResultCollection(false, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForListWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchCategorizedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, options)) .assertNext(response -> validateCategorizedEntitiesResultCollection(true, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void recognizeEntitiesBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(15, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(22, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(30, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(14, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(15, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(126, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesResolutions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeEntitiesBatchResolutionRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, options)) .assertNext(recognizeEntitiesResults -> validateEntityResolutions(recognizeEntitiesResults)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiSingleDocumentRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(response -> validatePiiEntities(getPiiEntitiesList1(), response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitySingleErrorRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .assertNext(resultCollection -> resultCollection.getValue().forEach(recognizePiiEntitiesResult -> { Exception exception = assertThrows(TextAnalyticsException.class, recognizePiiEntitiesResult::getEntities); assertEquals(String.format(BATCH_ERROR_EXCEPTION_MESSAGE, "RecognizePiiEntitiesResult"), exception.getMessage()); })).verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(false, getExpectedBatchPiiEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(true, getExpectedBatchPiiEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, language, null)) .assertNext(response -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, null, options)) .assertNext(response -> validatePiiEntitiesResultCollection(true, getExpectedBatchPiiEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(10, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(17, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(25, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(9, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(10, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(121, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiDomainFilterRunner((document, options) -> StepVerifier.create(client.recognizePiiEntities(document, "en", options)) .assertNext(response -> validatePiiEntities(getPiiEntitiesList1ForDomainFilter(), response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputStringForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, language, new RecognizePiiEntitiesOptions().setDomainFilter(PiiEntityDomain.PROTECTED_HEALTH_INFORMATION))) .assertNext(response -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForDomainFilter(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, new RecognizePiiEntitiesOptions().setDomainFilter(PiiEntityDomain.PROTECTED_HEALTH_INFORMATION))) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(false, getExpectedBatchPiiEntitiesForDomainFilter(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputForCategoriesFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesForCategoriesFilterRunner( (inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntityWithCategoriesFilterFromOtherResult(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesForCategoriesFilterRunner( (inputs, options) -> { List<PiiEntityCategory> categories = new ArrayList<>(); StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> { resultCollection.forEach(result -> result.getEntities().forEach(piiEntity -> { final PiiEntityCategory category = piiEntity.getCategory(); if (PiiEntityCategory.ABA_ROUTING_NUMBER == category || PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER == category) { categories.add(category); } })); validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection); }) .verifyComplete(); final PiiEntityCategory[] piiEntityCategories = categories.toArray(new PiiEntityCategory[categories.size()]); options.setCategoriesFilter(piiEntityCategories); StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedEntitiesForSingleTextInputRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .assertNext(response -> validateLinkedEntity(getLinkedEntitiesList1().get(0), response.iterator().next())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchLinkedEntityRunner((inputs) -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validateLinkedEntitiesResultCollectionWithResponse(false, getExpectedBatchLinkedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchLinkedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validateLinkedEntitiesResultCollectionWithResponse(true, getExpectedBatchLinkedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedStringInputRunner((inputs) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, null)) .assertNext(response -> validateLinkedEntitiesResultCollection(false, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, language, null)) .assertNext(response -> validateLinkedEntitiesResultCollection(false, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchStringLinkedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, options)) .assertNext(response -> validateLinkedEntitiesResultCollection(true, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(15, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(22, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(30, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(14, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(15, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(126, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesForSingleTextInputRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesCollection -> validateKeyPhrases(asList("monde"), keyPhrasesCollection.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchKeyPhrasesRunner((inputs) -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollectionWithResponse(false, getExpectedBatchKeyPhrases(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchKeyPhrasesShowStatsRunner((inputs, options) -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, options)) .assertNext(response -> validateExtractKeyPhrasesResultCollectionWithResponse(true, getExpectedBatchKeyPhrases(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesStringInputRunner((inputs) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(false, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesLanguageHintRunner((inputs, language) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, language, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(false, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchStringKeyPhrasesShowStatsRunner((inputs, options) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, options)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(true, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesWarningRunner( input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesResult -> { keyPhrasesResult.getWarnings().forEach(warning -> { assertTrue(WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE.equals(warning.getMessage())); assertTrue(LONG_WORDS_IN_DOCUMENT.equals(warning.getWarningCode())); }); }) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesBatchWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesBatchWarningRunner( inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .assertNext(response -> response.getValue().forEach(keyPhrasesResult -> keyPhrasesResult.getKeyPhrases().getWarnings().forEach(warning -> { assertTrue(WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE.equals(warning.getMessage())); assertTrue(LONG_WORDS_IN_DOCUMENT.equals(warning.getWarningCode())); }) )) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } /** * Test analyzing sentiment for a string input. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForSingleTextInputRunner(input -> StepVerifier.create(client.analyzeSentiment(input)) .assertNext(response -> validateDocumentSentiment(false, getExpectedDocumentSentiment(), response)) .verifyComplete() ); } /** * Test analyzing sentiment for a string input with default language hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInputWithDefaultLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForSingleTextInputRunner(input -> StepVerifier.create(client.analyzeSentiment(input, null)) .assertNext(response -> validateDocumentSentiment(false, getExpectedDocumentSentiment(), response)) .verifyComplete() ); } /** * Test analyzing sentiment for a string input and verifying the result of opinion mining. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInputWithOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForTextInputWithOpinionMiningRunner((input, options) -> StepVerifier.create(client.analyzeSentiment(input, "en", options)) .assertNext(response -> validateDocumentSentiment(true, getExpectedDocumentSentiment(), response)) .verifyComplete()); } /** * Verifies that an TextAnalyticsException is thrown for an empty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(document -> StepVerifier.create(client.analyzeSentiment(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } /** * Test analyzing sentiment for a duplicate ID list. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, new TextAnalyticsRequestOptions())) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } /** * Verifies that an invalid document exception is returned for input documents with an empty ID. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * String documents with null TextAnalyticsRequestOptions and null language code which will use the default language * code, 'en'. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null and null language code which will use the default language code, 'en'. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentStringInputRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, new TextAnalyticsRequestOptions())) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * String documents with null TextAnalyticsRequestOptions and given a language code. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null and given a language code. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringWithLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentLanguageHintRunner((inputs, language) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, language, new TextAnalyticsRequestOptions())) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result includes request statistics but not sentence options when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which to show the request statistics only and verify the analyzed sentiment result. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringShowStatisticsExcludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options.setIncludeOpinionMining(false))) .assertNext(response -> validateAnalyzeSentimentResultCollection(true, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result includes sentence options but not request statistics when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringNotShowStatisticsButIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> { options.setIncludeStatistics(false); StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options)) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, true, getExpectedBatchTextSentiment(), response)) .verifyComplete(); }); } /** * Verify that the collection result includes sentence options and request statistics when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringShowStatisticsAndIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options)) .assertNext(response -> validateAnalyzeSentimentResultCollection(true, true, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * TextDocumentInput documents with null TextAnalyticsRequestOptions. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputWithNullRequestOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, (TextAnalyticsRequestOptions) null)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that we can get statistics on the collection result when given a batch of * TextDocumentInput documents with TextAnalyticsRequestOptions. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions includes request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentShowStatsRunner((inputs, requestOptions) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, requestOptions)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * TextDocumentInput documents with null AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions is null. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputWithNullAnalyzeSentimentOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, (AnalyzeSentimentOptions) null)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result includes request statistics but not sentence options when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes request statistics but not opinion mining. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatisticsExcludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options.setIncludeOpinionMining(false))) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result includes sentence options but not request statistics when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining but not request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputNotShowStatisticsButIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> { options.setIncludeStatistics(false); StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, true, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete(); }); } /** * Verify that the collection result includes sentence options and request statistics when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatisticsAndIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, true, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verifies that an InvalidDocumentBatch exception is returned for input documents with too many documents. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(opinionSentiment -> { assertEquals(7, opinionSentiment.getLength()); assertEquals(17, opinionSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(27, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(19, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(9, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext( result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(34, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(26, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(16, targetSentiment.getOffset()); }); }) ) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext( result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(42, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(34, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(24, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(26, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(18, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(8, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(27, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(19, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(9, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(17, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(17, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(138, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(130, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(120, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareStringInputWithoutOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareStringInputRunner((documents, dummyOptions) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( false, getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareStringInputWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareStringInputRunner((documents, options) -> { boolean isValidApiVersionForDisplayName = serviceVersion != TextAnalyticsServiceVersion.V3_0 && serviceVersion != TextAnalyticsServiceVersion.V3_1; if (isValidApiVersionForDisplayName) { options.setDisplayName("operationName"); } SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<AnalyzeHealthcareEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); if (isValidApiVersionForDisplayName) { assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); } AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePageWithFhir(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareMaxOverload(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareLroRunner((documents, options) -> { boolean isValidApiVersionForDisplayName = serviceVersion != TextAnalyticsServiceVersion.V3_0 && serviceVersion != TextAnalyticsServiceVersion.V3_1; if (isValidApiVersionForDisplayName) { options.setDisplayName("operationName"); } SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<AnalyzeHealthcareEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); if (isValidApiVersionForDisplayName) { assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); } AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareLroPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareLroPaginationRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForMultiplePages(0, 10, 0), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }, 10); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareLroEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyListRunner((documents, errorMessage) -> { StepVerifier.create(client.beginAnalyzeHealthcareEntities(documents, null)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && errorMessage.equals(throwable.getMessage())) .verify(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void analyzeHealthcareEntitiesEmojiUnicodeCodePoint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(22, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(29, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(37, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(21, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(22, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(133, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesForAssertion(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeHealthcareEntitiesForAssertionRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); final HealthcareEntityAssertion assertion = analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList()) .get(0).stream().collect(Collectors.toList()) .get(0).getEntities().stream().collect(Collectors.toList()) .get(1) .getAssertion(); assertEquals(EntityConditionality.HYPOTHETICAL, assertion.getConditionality()); assertNull(assertion.getAssociation()); assertNull(assertion.getCertainty()); }); } @Disabled("Temporary disable it for green test") @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void cancelHealthcareLro(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); cancelHealthcareLroRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.cancelOperation(); LongRunningOperationStatus operationStatus = syncPoller.poll().getStatus(); while (!LongRunningOperationStatus.USER_CANCELLED.equals(operationStatus)) { operationStatus = syncPoller.poll().getStatus(); } syncPoller.waitForCompletion(); Assertions.assertEquals(LongRunningOperationStatus.USER_CANCELLED, operationStatus); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsStringInputRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForActions(), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getRecognizePiiEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchActionsRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForActions(), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getRecognizePiiEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithMultiSameKindActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsWithMultiSameKindActionsRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { assertEquals(2, actionsResult.getRecognizeEntitiesResults().stream().count()); assertEquals(2, actionsResult.getRecognizePiiEntitiesResults().stream().count()); assertEquals(2, actionsResult.getRecognizeLinkedEntitiesResults().stream().count()); assertEquals(2, actionsResult.getAnalyzeSentimentResults().stream().count()); assertEquals(2, actionsResult.getExtractKeyPhrasesResults().stream().count()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithActionNames(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsWithActionNamesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizeEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizePiiEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizeLinkedEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getAnalyzeSentimentResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getExtractKeyPhrasesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsAutoDetectedLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsAutoDetectedLanguageRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { List<RecognizeEntitiesResult> recognizeEntitiesResults = actionsResult.getRecognizeEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizeEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizeEntitiesResults.get(1).getDetectedLanguage()); List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = actionsResult.getRecognizePiiEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizePiiEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizePiiEntitiesResults.get(1).getDetectedLanguage()); List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResults = actionsResult.getRecognizeLinkedEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizeLinkedEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizeLinkedEntitiesResults.get(1).getDetectedLanguage()); List<AnalyzeSentimentResult> analyzeSentimentResults = actionsResult.getAnalyzeSentimentResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, analyzeSentimentResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, analyzeSentimentResults.get(1).getDetectedLanguage()); List<ExtractKeyPhraseResult> keyPhraseResults = actionsResult.getExtractKeyPhrasesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, keyPhraseResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, keyPhraseResults.get(1).getDetectedLanguage()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsAutoDetectedLanguageCustomTexts(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); analyzeActionsAutoDetectedLanguageCustomTextRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { List<RecognizeEntitiesResult> customEntitiesResults = actionsResult.getRecognizeCustomEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, customEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, customEntitiesResults.get(1).getDetectedLanguage()); List<ClassifyDocumentResult> singleLabelResults = actionsResult.getSingleLabelClassifyResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, singleLabelResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, singleLabelResults.get(1).getDetectedLanguage()); List<ClassifyDocumentResult> multiLabelResults = actionsResult.getMultiLabelClassifyResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, multiLabelResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, multiLabelResults.get(1).getDetectedLanguage()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchActionsPaginationRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions( documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, getExpectedAnalyzeActionsResultListForMultiplePages(0, 20, 2), result.toStream().collect(Collectors.toList())); }, 22); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyListRunner((documents, errorMessage) -> StepVerifier.create(client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setRecognizeEntitiesActions(new RecognizeEntitiesAction()), null)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && errorMessage.equals(throwable.getMessage())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeEntitiesRecognitionAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeEntitiesRecognitionRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeEntitiesRecognitionActionResolution(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeEntitiesRecognitionResolutionRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().forEach(actionsResult -> { actionsResult.getRecognizeEntitiesResults().forEach(nerActionResult -> { validateEntityResolutions(nerActionResult.getDocumentsResults()); }); }); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithCategoriesFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzePiiEntityRecognitionWithCategoriesFiltersRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForCategoriesFilter(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithDomainFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzePiiEntityRecognitionWithDomainFiltersRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForDomainFilter(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeLinkedEntityActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeLinkedEntityRecognitionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList( false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeKeyPhrasesExtractionAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getExpectedBatchTextSentiment(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeHealthcareEntitiesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedAnalyzeHealthcareEntitiesActionResult(false, null, TIME_NOW, getExpectedAnalyzeHealthcareEntitiesResultCollection(2, asList( getRecognizeHealthcareEntitiesResultWithFhir1("0"), getRecognizeHealthcareEntitiesResultWithFhir2())), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntitiesAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getRecognizeCustomEntitiesResults().forEach( customEntitiesActionResult -> customEntitiesActionResult.getDocumentsResults().forEach( documentResult -> validateCategorizedEntities( documentResult.getEntities().stream().collect(Collectors.toList()))))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassificationAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleCategoryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getSingleLabelClassifyResults().forEach( customSingleCategoryActionResult -> customSingleCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateLabelClassificationResult(documentResult)))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiCategoryClassifyAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiCategoryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getMultiLabelClassifyResults().forEach( customMultiCategoryActionResult -> customMultiCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateLabelClassificationResult(documentResult)))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntitiesStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesRunner((documents, parameters) -> { SyncPoller<RecognizeCustomEntitiesOperationDetail, RecognizeCustomEntitiesPagedFlux> syncPoller = client.beginRecognizeCustomEntities(documents, parameters.get(0), parameters.get(1)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); RecognizeCustomEntitiesPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateCategorizedEntities(documentResult.getEntities().stream().collect(Collectors.toList())))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntities(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesRunner((documents, parameters) -> { RecognizeCustomEntitiesOptions options = new RecognizeCustomEntitiesOptions() .setDisplayName("operationName"); SyncPoller<RecognizeCustomEntitiesOperationDetail, RecognizeCustomEntitiesPagedFlux> syncPoller = client.beginRecognizeCustomEntities(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<RecognizeCustomEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); RecognizeCustomEntitiesPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateCategorizedEntities(documentResult.getEntities().stream().collect(Collectors.toList())))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassificationStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleLabelRunner((documents, parameters) -> { SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginSingleLabelClassify(documents, parameters.get(0), parameters.get(1)) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassification(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleLabelRunner((documents, parameters) -> { SingleLabelClassifyOptions options = new SingleLabelClassifyOptions().setDisplayName("operationName"); SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginSingleLabelClassify(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<ClassifyDocumentOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiLabelClassificationStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiLabelRunner((documents, parameters) -> { SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginMultiLabelClassify(documents, parameters.get(0), parameters.get(1)) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiLabelClassification(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiLabelRunner((documents, parameters) -> { MultiLabelClassifyOptions options = new MultiLabelClassifyOptions().setDisplayName("operationName"); SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginMultiLabelClassify(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<ClassifyDocumentOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExtractSummaryActionResult(false, null, TIME_NOW, getExpectedExtractSummaryResultCollection(getExpectedExtractSummaryResultSortByOffset()), null))), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }, null, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionSortedByOffset(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue(isAscendingOrderByOffSet( documentResult.getSentences().stream().collect(Collectors.toList())))))); }, 4, SummarySentencesOrder.OFFSET); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionSortedByRankScore(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue(isDescendingOrderByRankScore( documentResult.getSentences().stream().collect(Collectors.toList())))))); }, 4, SummarySentencesOrder.RANK); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithSentenceCountLessThanMaxCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue( documentResult.getSentences().stream().collect(Collectors.toList()).size() < 20)))); }, 20, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithNonDefaultSentenceCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertEquals( documentResult.getSentences().stream().collect(Collectors.toList()).size(), 5)))); }, 5, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionMaxSentenceCountInvalidRangeException(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { extractSummaryActionRunner( (documents, tasks) -> { HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); }); assertEquals( TextAnalyticsErrorCode.INVALID_PARAMETER_VALUE, ((TextAnalyticsError) exception.getValue()).getErrorCode()); }, invalidCount, null); } } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeAbstractiveSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getAbstractSummaryActionResult(false, null, TIME_NOW, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), null ))) )), result.toStream().collect(Collectors.toList())); }, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryRunner((documents, options) -> { SyncPoller<AbstractSummaryOperationDetail, AbstractSummaryPagedFlux> syncPoller = client.beginAbstractSummary(documents) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AbstractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResult -> validateAbstractiveSummaryResultCollection(false, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), documentResult)); }, 4); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryMaxOverload(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryMaxOverloadRunner((documents, options) -> { SyncPoller<AbstractSummaryOperationDetail, AbstractSummaryPagedFlux> syncPoller = client.beginAbstractSummary(documents, options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AbstractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResult -> validateAbstractiveSummaryResultCollection(false, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), documentResult)); }, 4); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySortedByOffset(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( isAscendingOrderByOffSet(documentResult.getSentences().stream().collect(Collectors.toList()))) )); }, 4, SummarySentencesOrder.OFFSET); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySortedByRankScore(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( isDescendingOrderByRankScore(documentResult.getSentences().stream().collect(Collectors.toList()))) )); }, 4, SummarySentencesOrder.RANK); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySentenceCountLessThanMaxCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( documentResult.getSentences().stream().collect(Collectors.toList()).size() < 20))); }, 20, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummaryNonDefaultSentenceCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertEquals( documentResult.getSentences().stream().collect(Collectors.toList()).size(), 5))); }, 5, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummaryMaxSentenceCountInvalidRangeException(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { extractSummaryRunner( (documents, options) -> { HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); }); assertEquals( TextAnalyticsErrorCode.INVALID_PARAMETER_VALUE, ((TextAnalyticsError) exception.getValue()).getErrorCode()); }, invalidCount, null); } } }
All tests should start after the resource is dynamically allocated.
static void beforeAll() throws InterruptedException { TimeUnit.SECONDS.sleep(180); StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); }
TimeUnit.SECONDS.sleep(180);
static void beforeAll() throws InterruptedException { TimeUnit.SECONDS.sleep(180); StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } private TextAnalyticsAsyncClient getTextAnalyticsAsyncClient(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion, boolean isStaticResource) { return getTextAnalyticsClientBuilder( buildAsyncAssertingClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), serviceVersion, isStaticResource) .buildAsyncClient(); } /** * Verify that we can get statistics on the collection result when given a batch of documents with request options. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageShowStatisticsRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, options)) .assertNext(response -> validateDetectLanguageResultCollectionWithResponse(true, getExpectedBatchDetectedLanguages(), 200, response)) .verifyComplete()); } /** * Test to detect language for each {@code DetectLanguageResult} input of a batch. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageRunner((inputs) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, null)) .assertNext(response -> validateDetectLanguageResultCollectionWithResponse(false, getExpectedBatchDetectedLanguages(), 200, response)) .verifyComplete()); } /** * Test to detect language for each string input of batch with given country hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchListCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguagesCountryHintRunner((inputs, countryHint) -> StepVerifier.create(client.detectLanguageBatch(inputs, countryHint, null)) .assertNext(actualResults -> validateDetectLanguageResultCollection(false, getExpectedBatchDetectedLanguages(), actualResults)) .verifyComplete()); } /** * Test to detect language for each string input of batch with request options. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchListCountryHintWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguagesBatchListCountryHintWithOptionsRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatch(inputs, null, options)) .assertNext(response -> validateDetectLanguageResultCollection(true, getExpectedBatchDetectedLanguages(), response)) .verifyComplete()); } /** * Test to detect language for each string input of batch. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageStringInputRunner((inputs) -> StepVerifier.create(client.detectLanguageBatch(inputs, null, null)) .assertNext(response -> validateDetectLanguageResultCollection(false, getExpectedBatchDetectedLanguages(), response)) .verifyComplete()); } /** * Verifies that a single DetectedLanguage is returned for a document to detectLanguage. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectSingleTextLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectSingleTextLanguageRunner(input -> StepVerifier.create(client.detectLanguage(input)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageEnglish(), response)) .verifyComplete()); } /** * Verifies that an TextAnalyticsException is thrown for a document with invalid country hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageInvalidCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageInvalidCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_COUNTRY_HINT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that TextAnalyticsException is thrown for an empty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.detectLanguage(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that a bad request exception is returned for input documents with same ids. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageDuplicateIdRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, options)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } /** * Verifies that an invalid document exception is returned for input documents with an empty ID. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageInputEmptyIdRunner(inputs -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } /** * Verify that with countryHint with empty string will not throw exception. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageEmptyCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageSpanish(), response)) .verifyComplete()); } /** * Verify that with countryHint with "none" will not throw exception. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageNoneCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageNoneCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageSpanish(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntitiesForSingleTextInputRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .assertNext(response -> validateCategorizedEntities(response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntitySingleErrorRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .assertNext(resultCollection -> resultCollection.getValue().forEach(recognizeEntitiesResult -> { Exception exception = assertThrows(TextAnalyticsException.class, recognizeEntitiesResult::getEntities); assertEquals(String.format(BATCH_ERROR_EXCEPTION_MESSAGE, "RecognizeEntitiesResult"), exception.getMessage()); })).verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntityRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validateCategorizedEntitiesResultCollectionWithResponse(false, getExpectedBatchCategorizedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validateCategorizedEntitiesResultCollectionWithResponse(true, getExpectedBatchCategorizedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntityStringInputRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, null)) .assertNext(response -> validateCategorizedEntitiesResultCollection(false, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntitiesLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, language, null)) .assertNext(response -> validateCategorizedEntitiesResultCollection(false, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForListWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchCategorizedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, options)) .assertNext(response -> validateCategorizedEntitiesResultCollection(true, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void recognizeEntitiesBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(15, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(22, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(30, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(14, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(15, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(126, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesResolutions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeEntitiesBatchResolutionRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, options)) .assertNext(recognizeEntitiesResults -> validateEntityResolutions(recognizeEntitiesResults)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiSingleDocumentRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(response -> validatePiiEntities(getPiiEntitiesList1(), response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitySingleErrorRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .assertNext(resultCollection -> resultCollection.getValue().forEach(recognizePiiEntitiesResult -> { Exception exception = assertThrows(TextAnalyticsException.class, recognizePiiEntitiesResult::getEntities); assertEquals(String.format(BATCH_ERROR_EXCEPTION_MESSAGE, "RecognizePiiEntitiesResult"), exception.getMessage()); })).verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(false, getExpectedBatchPiiEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(true, getExpectedBatchPiiEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, language, null)) .assertNext(response -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, null, options)) .assertNext(response -> validatePiiEntitiesResultCollection(true, getExpectedBatchPiiEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(10, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(17, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(25, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(9, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(10, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(121, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiDomainFilterRunner((document, options) -> StepVerifier.create(client.recognizePiiEntities(document, "en", options)) .assertNext(response -> validatePiiEntities(getPiiEntitiesList1ForDomainFilter(), response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputStringForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, language, new RecognizePiiEntitiesOptions().setDomainFilter(PiiEntityDomain.PROTECTED_HEALTH_INFORMATION))) .assertNext(response -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForDomainFilter(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, new RecognizePiiEntitiesOptions().setDomainFilter(PiiEntityDomain.PROTECTED_HEALTH_INFORMATION))) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(false, getExpectedBatchPiiEntitiesForDomainFilter(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputForCategoriesFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesForCategoriesFilterRunner( (inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntityWithCategoriesFilterFromOtherResult(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesForCategoriesFilterRunner( (inputs, options) -> { List<PiiEntityCategory> categories = new ArrayList<>(); StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> { resultCollection.forEach(result -> result.getEntities().forEach(piiEntity -> { final PiiEntityCategory category = piiEntity.getCategory(); if (PiiEntityCategory.ABA_ROUTING_NUMBER == category || PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER == category) { categories.add(category); } })); validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection); }) .verifyComplete(); final PiiEntityCategory[] piiEntityCategories = categories.toArray(new PiiEntityCategory[categories.size()]); options.setCategoriesFilter(piiEntityCategories); StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedEntitiesForSingleTextInputRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .assertNext(response -> validateLinkedEntity(getLinkedEntitiesList1().get(0), response.iterator().next())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchLinkedEntityRunner((inputs) -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validateLinkedEntitiesResultCollectionWithResponse(false, getExpectedBatchLinkedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchLinkedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validateLinkedEntitiesResultCollectionWithResponse(true, getExpectedBatchLinkedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedStringInputRunner((inputs) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, null)) .assertNext(response -> validateLinkedEntitiesResultCollection(false, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, language, null)) .assertNext(response -> validateLinkedEntitiesResultCollection(false, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchStringLinkedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, options)) .assertNext(response -> validateLinkedEntitiesResultCollection(true, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(15, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(22, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(30, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(14, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(15, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(126, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesForSingleTextInputRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesCollection -> validateKeyPhrases(asList("monde"), keyPhrasesCollection.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchKeyPhrasesRunner((inputs) -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollectionWithResponse(false, getExpectedBatchKeyPhrases(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchKeyPhrasesShowStatsRunner((inputs, options) -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, options)) .assertNext(response -> validateExtractKeyPhrasesResultCollectionWithResponse(true, getExpectedBatchKeyPhrases(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesStringInputRunner((inputs) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(false, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesLanguageHintRunner((inputs, language) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, language, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(false, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchStringKeyPhrasesShowStatsRunner((inputs, options) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, options)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(true, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesWarningRunner( input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesResult -> { keyPhrasesResult.getWarnings().forEach(warning -> { assertTrue(WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE.equals(warning.getMessage())); assertTrue(LONG_WORDS_IN_DOCUMENT.equals(warning.getWarningCode())); }); }) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesBatchWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesBatchWarningRunner( inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .assertNext(response -> response.getValue().forEach(keyPhrasesResult -> keyPhrasesResult.getKeyPhrases().getWarnings().forEach(warning -> { assertTrue(WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE.equals(warning.getMessage())); assertTrue(LONG_WORDS_IN_DOCUMENT.equals(warning.getWarningCode())); }) )) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } /** * Test analyzing sentiment for a string input. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForSingleTextInputRunner(input -> StepVerifier.create(client.analyzeSentiment(input)) .assertNext(response -> validateDocumentSentiment(false, getExpectedDocumentSentiment(), response)) .verifyComplete() ); } /** * Test analyzing sentiment for a string input with default language hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInputWithDefaultLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForSingleTextInputRunner(input -> StepVerifier.create(client.analyzeSentiment(input, null)) .assertNext(response -> validateDocumentSentiment(false, getExpectedDocumentSentiment(), response)) .verifyComplete() ); } /** * Test analyzing sentiment for a string input and verifying the result of opinion mining. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInputWithOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForTextInputWithOpinionMiningRunner((input, options) -> StepVerifier.create(client.analyzeSentiment(input, "en", options)) .assertNext(response -> validateDocumentSentiment(true, getExpectedDocumentSentiment(), response)) .verifyComplete()); } /** * Verifies that an TextAnalyticsException is thrown for an empty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(document -> StepVerifier.create(client.analyzeSentiment(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } /** * Test analyzing sentiment for a duplicate ID list. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, new TextAnalyticsRequestOptions())) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } /** * Verifies that an invalid document exception is returned for input documents with an empty ID. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * String documents with null TextAnalyticsRequestOptions and null language code which will use the default language * code, 'en'. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null and null language code which will use the default language code, 'en'. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentStringInputRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, new TextAnalyticsRequestOptions())) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * String documents with null TextAnalyticsRequestOptions and given a language code. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null and given a language code. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringWithLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentLanguageHintRunner((inputs, language) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, language, new TextAnalyticsRequestOptions())) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result includes request statistics but not sentence options when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which to show the request statistics only and verify the analyzed sentiment result. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringShowStatisticsExcludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options.setIncludeOpinionMining(false))) .assertNext(response -> validateAnalyzeSentimentResultCollection(true, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result includes sentence options but not request statistics when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringNotShowStatisticsButIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> { options.setIncludeStatistics(false); StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options)) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, true, getExpectedBatchTextSentiment(), response)) .verifyComplete(); }); } /** * Verify that the collection result includes sentence options and request statistics when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringShowStatisticsAndIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options)) .assertNext(response -> validateAnalyzeSentimentResultCollection(true, true, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * TextDocumentInput documents with null TextAnalyticsRequestOptions. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputWithNullRequestOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, (TextAnalyticsRequestOptions) null)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that we can get statistics on the collection result when given a batch of * TextDocumentInput documents with TextAnalyticsRequestOptions. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions includes request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentShowStatsRunner((inputs, requestOptions) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, requestOptions)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * TextDocumentInput documents with null AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions is null. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputWithNullAnalyzeSentimentOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, (AnalyzeSentimentOptions) null)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result includes request statistics but not sentence options when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes request statistics but not opinion mining. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatisticsExcludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options.setIncludeOpinionMining(false))) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result includes sentence options but not request statistics when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining but not request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputNotShowStatisticsButIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> { options.setIncludeStatistics(false); StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, true, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete(); }); } /** * Verify that the collection result includes sentence options and request statistics when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatisticsAndIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, true, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verifies that an InvalidDocumentBatch exception is returned for input documents with too many documents. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(opinionSentiment -> { assertEquals(7, opinionSentiment.getLength()); assertEquals(17, opinionSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(27, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(19, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(9, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext( result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(34, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(26, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(16, targetSentiment.getOffset()); }); }) ) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext( result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(42, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(34, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(24, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(26, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(18, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(8, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(27, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(19, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(9, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(17, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(17, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(138, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(130, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(120, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareStringInputWithoutOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareStringInputRunner((documents, dummyOptions) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( false, getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareStringInputWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareStringInputRunner((documents, options) -> { boolean isValidApiVersionForDisplayName = serviceVersion != TextAnalyticsServiceVersion.V3_0 && serviceVersion != TextAnalyticsServiceVersion.V3_1; if (isValidApiVersionForDisplayName) { options.setDisplayName("operationName"); } SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<AnalyzeHealthcareEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); if (isValidApiVersionForDisplayName) { assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); } AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePageWithFhir(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareMaxOverload(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareLroRunner((documents, options) -> { boolean isValidApiVersionForDisplayName = serviceVersion != TextAnalyticsServiceVersion.V3_0 && serviceVersion != TextAnalyticsServiceVersion.V3_1; if (isValidApiVersionForDisplayName) { options.setDisplayName("operationName"); } SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<AnalyzeHealthcareEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); if (isValidApiVersionForDisplayName) { assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); } AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareLroPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareLroPaginationRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForMultiplePages(0, 10, 0), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }, 10); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareLroEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyListRunner((documents, errorMessage) -> { StepVerifier.create(client.beginAnalyzeHealthcareEntities(documents, null)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && errorMessage.equals(throwable.getMessage())) .verify(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void analyzeHealthcareEntitiesEmojiUnicodeCodePoint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(22, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(29, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(37, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(21, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(22, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(133, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesForAssertion(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeHealthcareEntitiesForAssertionRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); final HealthcareEntityAssertion assertion = analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList()) .get(0).stream().collect(Collectors.toList()) .get(0).getEntities().stream().collect(Collectors.toList()) .get(1) .getAssertion(); assertEquals(EntityConditionality.HYPOTHETICAL, assertion.getConditionality()); assertNull(assertion.getAssociation()); assertNull(assertion.getCertainty()); }); } @Disabled("Temporary disable it for green test") @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void cancelHealthcareLro(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); cancelHealthcareLroRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.cancelOperation(); LongRunningOperationStatus operationStatus = syncPoller.poll().getStatus(); while (!LongRunningOperationStatus.USER_CANCELLED.equals(operationStatus)) { operationStatus = syncPoller.poll().getStatus(); } syncPoller.waitForCompletion(); Assertions.assertEquals(LongRunningOperationStatus.USER_CANCELLED, operationStatus); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsStringInputRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForActions(), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getRecognizePiiEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchActionsRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForActions(), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getRecognizePiiEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithMultiSameKindActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsWithMultiSameKindActionsRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { assertEquals(2, actionsResult.getRecognizeEntitiesResults().stream().count()); assertEquals(2, actionsResult.getRecognizePiiEntitiesResults().stream().count()); assertEquals(2, actionsResult.getRecognizeLinkedEntitiesResults().stream().count()); assertEquals(2, actionsResult.getAnalyzeSentimentResults().stream().count()); assertEquals(2, actionsResult.getExtractKeyPhrasesResults().stream().count()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithActionNames(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsWithActionNamesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizeEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizePiiEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizeLinkedEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getAnalyzeSentimentResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getExtractKeyPhrasesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsAutoDetectedLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsAutoDetectedLanguageRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { List<RecognizeEntitiesResult> recognizeEntitiesResults = actionsResult.getRecognizeEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizeEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizeEntitiesResults.get(1).getDetectedLanguage()); List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = actionsResult.getRecognizePiiEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizePiiEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizePiiEntitiesResults.get(1).getDetectedLanguage()); List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResults = actionsResult.getRecognizeLinkedEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizeLinkedEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizeLinkedEntitiesResults.get(1).getDetectedLanguage()); List<AnalyzeSentimentResult> analyzeSentimentResults = actionsResult.getAnalyzeSentimentResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, analyzeSentimentResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, analyzeSentimentResults.get(1).getDetectedLanguage()); List<ExtractKeyPhraseResult> keyPhraseResults = actionsResult.getExtractKeyPhrasesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, keyPhraseResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, keyPhraseResults.get(1).getDetectedLanguage()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsAutoDetectedLanguageCustomTexts(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); analyzeActionsAutoDetectedLanguageCustomTextRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { List<RecognizeEntitiesResult> customEntitiesResults = actionsResult.getRecognizeCustomEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, customEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, customEntitiesResults.get(1).getDetectedLanguage()); List<ClassifyDocumentResult> singleLabelResults = actionsResult.getSingleLabelClassifyResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, singleLabelResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, singleLabelResults.get(1).getDetectedLanguage()); List<ClassifyDocumentResult> multiLabelResults = actionsResult.getMultiLabelClassifyResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, multiLabelResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, multiLabelResults.get(1).getDetectedLanguage()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchActionsPaginationRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions( documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, getExpectedAnalyzeActionsResultListForMultiplePages(0, 20, 2), result.toStream().collect(Collectors.toList())); }, 22); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyListRunner((documents, errorMessage) -> StepVerifier.create(client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setRecognizeEntitiesActions(new RecognizeEntitiesAction()), null)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && errorMessage.equals(throwable.getMessage())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeEntitiesRecognitionAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeEntitiesRecognitionRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeEntitiesRecognitionActionResolution(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeEntitiesRecognitionResolutionRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().forEach(actionsResult -> { actionsResult.getRecognizeEntitiesResults().forEach(nerActionResult -> { validateEntityResolutions(nerActionResult.getDocumentsResults()); }); }); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithCategoriesFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzePiiEntityRecognitionWithCategoriesFiltersRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForCategoriesFilter(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithDomainFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzePiiEntityRecognitionWithDomainFiltersRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForDomainFilter(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeLinkedEntityActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeLinkedEntityRecognitionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList( false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeKeyPhrasesExtractionAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getExpectedBatchTextSentiment(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeHealthcareEntitiesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedAnalyzeHealthcareEntitiesActionResult(false, null, TIME_NOW, getExpectedAnalyzeHealthcareEntitiesResultCollection(2, asList( getRecognizeHealthcareEntitiesResultWithFhir1("0"), getRecognizeHealthcareEntitiesResultWithFhir2())), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntitiesAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getRecognizeCustomEntitiesResults().forEach( customEntitiesActionResult -> customEntitiesActionResult.getDocumentsResults().forEach( documentResult -> validateCategorizedEntities( documentResult.getEntities().stream().collect(Collectors.toList()))))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassificationAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleCategoryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getSingleLabelClassifyResults().forEach( customSingleCategoryActionResult -> customSingleCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateLabelClassificationResult(documentResult)))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiCategoryClassifyAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiCategoryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getMultiLabelClassifyResults().forEach( customMultiCategoryActionResult -> customMultiCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateLabelClassificationResult(documentResult)))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntitiesStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesRunner((documents, parameters) -> { SyncPoller<RecognizeCustomEntitiesOperationDetail, RecognizeCustomEntitiesPagedFlux> syncPoller = client.beginRecognizeCustomEntities(documents, parameters.get(0), parameters.get(1)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); RecognizeCustomEntitiesPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateCategorizedEntities(documentResult.getEntities().stream().collect(Collectors.toList())))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntities(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesRunner((documents, parameters) -> { RecognizeCustomEntitiesOptions options = new RecognizeCustomEntitiesOptions() .setDisplayName("operationName"); SyncPoller<RecognizeCustomEntitiesOperationDetail, RecognizeCustomEntitiesPagedFlux> syncPoller = client.beginRecognizeCustomEntities(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<RecognizeCustomEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); RecognizeCustomEntitiesPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateCategorizedEntities(documentResult.getEntities().stream().collect(Collectors.toList())))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassificationStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleLabelRunner((documents, parameters) -> { SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginSingleLabelClassify(documents, parameters.get(0), parameters.get(1)) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassification(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleLabelRunner((documents, parameters) -> { SingleLabelClassifyOptions options = new SingleLabelClassifyOptions().setDisplayName("operationName"); SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginSingleLabelClassify(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<ClassifyDocumentOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiLabelClassificationStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiLabelRunner((documents, parameters) -> { SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginMultiLabelClassify(documents, parameters.get(0), parameters.get(1)) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiLabelClassification(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiLabelRunner((documents, parameters) -> { MultiLabelClassifyOptions options = new MultiLabelClassifyOptions().setDisplayName("operationName"); SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginMultiLabelClassify(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<ClassifyDocumentOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExtractSummaryActionResult(false, null, TIME_NOW, getExpectedExtractSummaryResultCollection(getExpectedExtractSummaryResultSortByOffset()), null))), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }, null, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionSortedByOffset(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue(isAscendingOrderByOffSet( documentResult.getSentences().stream().collect(Collectors.toList())))))); }, 4, SummarySentencesOrder.OFFSET); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionSortedByRankScore(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue(isDescendingOrderByRankScore( documentResult.getSentences().stream().collect(Collectors.toList())))))); }, 4, SummarySentencesOrder.RANK); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithSentenceCountLessThanMaxCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue( documentResult.getSentences().stream().collect(Collectors.toList()).size() < 20)))); }, 20, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithNonDefaultSentenceCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertEquals( documentResult.getSentences().stream().collect(Collectors.toList()).size(), 5)))); }, 5, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionMaxSentenceCountInvalidRangeException(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { extractSummaryActionRunner( (documents, tasks) -> { HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); }); assertEquals( TextAnalyticsErrorCode.INVALID_PARAMETER_VALUE, ((TextAnalyticsError) exception.getValue()).getErrorCode()); }, invalidCount, null); } } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeAbstractiveSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getAbstractSummaryActionResult(false, null, TIME_NOW, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), null ))) )), result.toStream().collect(Collectors.toList())); }, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryRunner((documents, options) -> { SyncPoller<AbstractSummaryOperationDetail, AbstractSummaryPagedFlux> syncPoller = client.beginAbstractSummary(documents) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AbstractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResult -> validateAbstractiveSummaryResultCollection(false, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), documentResult)); }, 4); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryMaxOverload(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryMaxOverloadRunner((documents, options) -> { SyncPoller<AbstractSummaryOperationDetail, AbstractSummaryPagedFlux> syncPoller = client.beginAbstractSummary(documents, options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AbstractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResult -> validateAbstractiveSummaryResultCollection(false, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), documentResult)); }, 4); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySortedByOffset(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( isAscendingOrderByOffSet(documentResult.getSentences().stream().collect(Collectors.toList()))) )); }, 4, SummarySentencesOrder.OFFSET); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySortedByRankScore(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( isDescendingOrderByRankScore(documentResult.getSentences().stream().collect(Collectors.toList()))) )); }, 4, SummarySentencesOrder.RANK); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySentenceCountLessThanMaxCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( documentResult.getSentences().stream().collect(Collectors.toList()).size() < 20))); }, 20, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummaryNonDefaultSentenceCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertEquals( documentResult.getSentences().stream().collect(Collectors.toList()).size(), 5))); }, 5, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummaryMaxSentenceCountInvalidRangeException(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { extractSummaryRunner( (documents, options) -> { HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); }); assertEquals( TextAnalyticsErrorCode.INVALID_PARAMETER_VALUE, ((TextAnalyticsError) exception.getValue()).getErrorCode()); }, invalidCount, null); } } }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } private HttpClient buildAsyncAssertingClient(HttpClient httpClient) { return new AssertingHttpClientBuilder(httpClient) .skipRequest((ignored1, ignored2) -> false) .assertAsync() .build(); } private TextAnalyticsAsyncClient getTextAnalyticsAsyncClient(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion, boolean isStaticResource) { return getTextAnalyticsClientBuilder( buildAsyncAssertingClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient), serviceVersion, isStaticResource) .buildAsyncClient(); } /** * Verify that we can get statistics on the collection result when given a batch of documents with request options. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageShowStatisticsRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, options)) .assertNext(response -> validateDetectLanguageResultCollectionWithResponse(true, getExpectedBatchDetectedLanguages(), 200, response)) .verifyComplete()); } /** * Test to detect language for each {@code DetectLanguageResult} input of a batch. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageRunner((inputs) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, null)) .assertNext(response -> validateDetectLanguageResultCollectionWithResponse(false, getExpectedBatchDetectedLanguages(), 200, response)) .verifyComplete()); } /** * Test to detect language for each string input of batch with given country hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchListCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguagesCountryHintRunner((inputs, countryHint) -> StepVerifier.create(client.detectLanguageBatch(inputs, countryHint, null)) .assertNext(actualResults -> validateDetectLanguageResultCollection(false, getExpectedBatchDetectedLanguages(), actualResults)) .verifyComplete()); } /** * Test to detect language for each string input of batch with request options. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchListCountryHintWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguagesBatchListCountryHintWithOptionsRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatch(inputs, null, options)) .assertNext(response -> validateDetectLanguageResultCollection(true, getExpectedBatchDetectedLanguages(), response)) .verifyComplete()); } /** * Test to detect language for each string input of batch. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguagesBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageStringInputRunner((inputs) -> StepVerifier.create(client.detectLanguageBatch(inputs, null, null)) .assertNext(response -> validateDetectLanguageResultCollection(false, getExpectedBatchDetectedLanguages(), response)) .verifyComplete()); } /** * Verifies that a single DetectedLanguage is returned for a document to detectLanguage. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectSingleTextLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectSingleTextLanguageRunner(input -> StepVerifier.create(client.detectLanguage(input)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageEnglish(), response)) .verifyComplete()); } /** * Verifies that an TextAnalyticsException is thrown for a document with invalid country hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageInvalidCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageInvalidCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_COUNTRY_HINT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that TextAnalyticsException is thrown for an empty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.detectLanguage(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } /** * Verifies that a bad request exception is returned for input documents with same ids. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageDuplicateIdRunner((inputs, options) -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, options)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } /** * Verifies that an invalid document exception is returned for input documents with an empty ID. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageInputEmptyIdRunner(inputs -> StepVerifier.create(client.detectLanguageBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } /** * Verify that with countryHint with empty string will not throw exception. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageEmptyCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageEmptyCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageSpanish(), response)) .verifyComplete()); } /** * Verify that with countryHint with "none" will not throw exception. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void detectLanguageNoneCountryHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); detectLanguageNoneCountryHintRunner((input, countryHint) -> StepVerifier.create(client.detectLanguage(input, countryHint)) .assertNext(response -> validatePrimaryLanguage(getDetectedLanguageSpanish(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntitiesForSingleTextInputRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .assertNext(response -> validateCategorizedEntities(response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.recognizeEntities(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntitySingleErrorRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .assertNext(resultCollection -> resultCollection.getValue().forEach(recognizeEntitiesResult -> { Exception exception = assertThrows(TextAnalyticsException.class, recognizeEntitiesResult::getEntities); assertEquals(String.format(BATCH_ERROR_EXCEPTION_MESSAGE, "RecognizeEntitiesResult"), exception.getMessage()); })).verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntityRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validateCategorizedEntitiesResultCollectionWithResponse(false, getExpectedBatchCategorizedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchCategorizedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validateCategorizedEntitiesResultCollectionWithResponse(true, getExpectedBatchCategorizedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntityStringInputRunner((inputs) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, null)) .assertNext(response -> validateCategorizedEntitiesResultCollection(false, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeCategorizedEntitiesLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, language, null)) .assertNext(response -> validateCategorizedEntitiesResultCollection(false, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesForListWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchCategorizedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, options)) .assertNext(response -> validateCategorizedEntitiesResultCollection(true, getExpectedBatchCategorizedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void recognizeEntitiesBatchWithResponseEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(15, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(22, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(30, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(14, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(15, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(13, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizeEntities(document)) .assertNext(result -> result.forEach(categorizedEntity -> { assertEquals(9, categorizedEntity.getLength()); assertEquals(126, categorizedEntity.getOffset()); })).verifyComplete(), CATEGORIZED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeEntitiesResolutions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeEntitiesBatchResolutionRunner((inputs, options) -> StepVerifier.create(client.recognizeEntitiesBatch(inputs, null, options)) .assertNext(recognizeEntitiesResults -> validateEntityResolutions(recognizeEntitiesResults)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiSingleDocumentRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(response -> validatePiiEntities(getPiiEntitiesList1(), response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesBatchInputSingleError(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitySingleErrorRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .assertNext(resultCollection -> resultCollection.getValue().forEach(recognizePiiEntitiesResult -> { Exception exception = assertThrows(TextAnalyticsException.class, recognizePiiEntitiesResult::getEntities); assertEquals(String.format(BATCH_ERROR_EXCEPTION_MESSAGE, "RecognizePiiEntitiesResult"), exception.getMessage()); })).verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(false, getExpectedBatchPiiEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(true, getExpectedBatchPiiEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, language, null)) .assertNext(response -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, null, options)) .assertNext(response -> validatePiiEntitiesResultCollection(true, getExpectedBatchPiiEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(10, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(17, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(25, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(9, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(10, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(8, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizePiiEntities(document)) .assertNext(result -> result.forEach(piiEntity -> { assertEquals(11, piiEntity.getLength()); assertEquals(121, piiEntity.getOffset()); })).verifyComplete(), PII_ENTITY_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiDomainFilterRunner((document, options) -> StepVerifier.create(client.recognizePiiEntities(document, "en", options)) .assertNext(response -> validatePiiEntities(getPiiEntitiesList1ForDomainFilter(), response.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputStringForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizePiiLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, language, new RecognizePiiEntitiesOptions().setDomainFilter(PiiEntityDomain.PROTECTED_HEALTH_INFORMATION))) .assertNext(response -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForDomainFilter(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputForDomainFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchPiiEntitiesRunner((inputs) -> StepVerifier.create(client.recognizePiiEntitiesBatchWithResponse(inputs, new RecognizePiiEntitiesOptions().setDomainFilter(PiiEntityDomain.PROTECTED_HEALTH_INFORMATION))) .assertNext(response -> validatePiiEntitiesResultCollectionWithResponse(false, getExpectedBatchPiiEntitiesForDomainFilter(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntitiesForBatchInputForCategoriesFilter(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesForCategoriesFilterRunner( (inputs, options) -> StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizePiiEntityWithCategoriesFilterFromOtherResult(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeStringBatchPiiEntitiesForCategoriesFilterRunner( (inputs, options) -> { List<PiiEntityCategory> categories = new ArrayList<>(); StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> { resultCollection.forEach(result -> result.getEntities().forEach(piiEntity -> { final PiiEntityCategory category = piiEntity.getCategory(); if (PiiEntityCategory.ABA_ROUTING_NUMBER == category || PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER == category) { categories.add(category); } })); validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection); }) .verifyComplete(); final PiiEntityCategory[] piiEntityCategories = categories.toArray(new PiiEntityCategory[categories.size()]); options.setCategoriesFilter(piiEntityCategories); StepVerifier.create(client.recognizePiiEntitiesBatch(inputs, "en", options)) .assertNext( resultCollection -> validatePiiEntitiesResultCollection(false, getExpectedBatchPiiEntitiesForCategoriesFilter(), resultCollection)) .verifyComplete(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedEntitiesForSingleTextInputRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .assertNext(response -> validateLinkedEntity(getLinkedEntitiesList1().get(0), response.iterator().next())) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.recognizeLinkedEntities(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchLinkedEntityRunner((inputs) -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, null)) .assertNext(response -> validateLinkedEntitiesResultCollectionWithResponse(false, getExpectedBatchLinkedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchLinkedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeLinkedEntitiesBatchWithResponse(inputs, options)) .assertNext(response -> validateLinkedEntitiesResultCollectionWithResponse(true, getExpectedBatchLinkedEntities(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedStringInputRunner((inputs) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, null)) .assertNext(response -> validateLinkedEntitiesResultCollection(false, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeLinkedLanguageHintRunner((inputs, language) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, language, null)) .assertNext(response -> validateLinkedEntitiesResultCollection(false, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); recognizeBatchStringLinkedEntitiesShowStatsRunner((inputs, options) -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, options)) .assertNext(response -> validateLinkedEntitiesResultCollection(true, getExpectedBatchLinkedEntities(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.recognizeLinkedEntitiesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(15, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(22, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesEmojiFamilyWIthSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(30, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(14, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(15, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(13, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeLinkedEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner(document -> StepVerifier.create(client.recognizeLinkedEntities(document)) .assertNext(result -> result.forEach(linkedEntity -> { linkedEntity.getMatches().forEach(linkedEntityMatch -> { assertEquals(9, linkedEntityMatch.getLength()); assertEquals(126, linkedEntityMatch.getOffset()); }); })).verifyComplete(), LINKED_ENTITY_INPUTS.get(1) ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesForSingleTextInputRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesCollection -> validateKeyPhrases(asList("monde"), keyPhrasesCollection.stream().collect(Collectors.toList()))) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(input -> StepVerifier.create(client.extractKeyPhrases(input)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchKeyPhrasesRunner((inputs) -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollectionWithResponse(false, getExpectedBatchKeyPhrases(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchKeyPhrasesShowStatsRunner((inputs, options) -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, options)) .assertNext(response -> validateExtractKeyPhrasesResultCollectionWithResponse(true, getExpectedBatchKeyPhrases(), 200, response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesStringInputRunner((inputs) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(false, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForListLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesLanguageHintRunner((inputs, language) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, language, null)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(false, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesForListStringWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractBatchStringKeyPhrasesShowStatsRunner((inputs, options) -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, options)) .assertNext(response -> validateExtractKeyPhrasesResultCollection(true, getExpectedBatchKeyPhrases(), response)) .verifyComplete()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesWarningRunner( input -> StepVerifier.create(client.extractKeyPhrases(input)) .assertNext(keyPhrasesResult -> { keyPhrasesResult.getWarnings().forEach(warning -> { assertTrue(WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE.equals(warning.getMessage())); assertTrue(LONG_WORDS_IN_DOCUMENT.equals(warning.getWarningCode())); }); }) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesBatchWarning(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesBatchWarningRunner( inputs -> StepVerifier.create(client.extractKeyPhrasesBatchWithResponse(inputs, null)) .assertNext(response -> response.getValue().forEach(keyPhrasesResult -> keyPhrasesResult.getKeyPhrases().getWarnings().forEach(warning -> { assertTrue(WARNING_TOO_LONG_DOCUMENT_INPUT_MESSAGE.equals(warning.getMessage())); assertTrue(LONG_WORDS_IN_DOCUMENT.equals(warning.getWarningCode())); }) )) .verifyComplete() ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void extractKeyPhrasesBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.extractKeyPhrasesBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } /** * Test analyzing sentiment for a string input. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForSingleTextInputRunner(input -> StepVerifier.create(client.analyzeSentiment(input)) .assertNext(response -> validateDocumentSentiment(false, getExpectedDocumentSentiment(), response)) .verifyComplete() ); } /** * Test analyzing sentiment for a string input with default language hint. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInputWithDefaultLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForSingleTextInputRunner(input -> StepVerifier.create(client.analyzeSentiment(input, null)) .assertNext(response -> validateDocumentSentiment(false, getExpectedDocumentSentiment(), response)) .verifyComplete() ); } /** * Test analyzing sentiment for a string input and verifying the result of opinion mining. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForTextInputWithOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentForTextInputWithOpinionMiningRunner((input, options) -> StepVerifier.create(client.analyzeSentiment(input, "en", options)) .assertNext(response -> validateDocumentSentiment(true, getExpectedDocumentSentiment(), response)) .verifyComplete()); } /** * Verifies that an TextAnalyticsException is thrown for an empty document. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForEmptyText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyTextRunner(document -> StepVerifier.create(client.analyzeSentiment(document)) .expectErrorMatches(throwable -> throwable instanceof TextAnalyticsException && INVALID_DOCUMENT.equals(((TextAnalyticsException) throwable).getErrorCode())) .verify() ); } /** * Test analyzing sentiment for a duplicate ID list. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, new TextAnalyticsRequestOptions())) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass()))); } /** * Verifies that an invalid document exception is returned for input documents with an empty ID. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); })); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * String documents with null TextAnalyticsRequestOptions and null language code which will use the default language * code, 'en'. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null and null language code which will use the default language code, 'en'. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentStringInputRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, new TextAnalyticsRequestOptions())) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * String documents with null TextAnalyticsRequestOptions and given a language code. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null and given a language code. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringWithLanguageHint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentLanguageHintRunner((inputs, language) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, language, new TextAnalyticsRequestOptions())) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result includes request statistics but not sentence options when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which to show the request statistics only and verify the analyzed sentiment result. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringShowStatisticsExcludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options.setIncludeOpinionMining(false))) .assertNext(response -> validateAnalyzeSentimentResultCollection(true, false, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result includes sentence options but not request statistics when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringNotShowStatisticsButIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> { options.setIncludeStatistics(false); StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options)) .assertNext(response -> validateAnalyzeSentimentResultCollection(false, true, getExpectedBatchTextSentiment(), response)) .verifyComplete(); }); } /** * Verify that the collection result includes sentence options and request statistics when given a batch of * String documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForListStringShowStatisticsAndIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchStringSentimentShowStatsAndIncludeOpinionMiningRunner((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, options)) .assertNext(response -> validateAnalyzeSentimentResultCollection(true, true, getExpectedBatchTextSentiment(), response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * TextDocumentInput documents with null TextAnalyticsRequestOptions. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions is null. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputWithNullRequestOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, (TextAnalyticsRequestOptions) null)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that we can get statistics on the collection result when given a batch of * TextDocumentInput documents with TextAnalyticsRequestOptions. * * {@link TextAnalyticsAsyncClient * which TextAnalyticsRequestOptions includes request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatistics(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentShowStatsRunner((inputs, requestOptions) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, requestOptions)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result excludes request statistics and sentence options when given a batch of * TextDocumentInput documents with null AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions is null. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputWithNullAnalyzeSentimentOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, (AnalyzeSentimentOptions) null)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result includes request statistics but not sentence options when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes request statistics but not opinion mining. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatisticsExcludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options.setIncludeOpinionMining(false))) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, false, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verify that the collection result includes sentence options but not request statistics when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining but not request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputNotShowStatisticsButIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> { options.setIncludeStatistics(false); StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(false, true, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete(); }); } /** * Verify that the collection result includes sentence options and request statistics when given a batch of * TextDocumentInput documents with AnalyzeSentimentOptions. * * {@link TextAnalyticsAsyncClient * which AnalyzeSentimentOptions includes opinion mining and request statistics. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentForBatchInputShowStatisticsAndIncludeOpinionMining(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchSentimentOpinionMining((inputs, options) -> StepVerifier.create(client.analyzeSentimentBatchWithResponse(inputs, options)) .assertNext(response -> validateAnalyzeSentimentResultCollectionWithResponse(true, true, getExpectedBatchTextSentiment(), 200, response)) .verifyComplete()); } /** * Verifies that an InvalidDocumentBatch exception is returned for input documents with too many documents. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentBatchTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> StepVerifier.create(client.analyzeSentimentBatch(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); })); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(opinionSentiment -> { assertEquals(7, opinionSentiment.getLength()); assertEquals(17, opinionSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(27, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(19, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(9, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext( result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(34, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(26, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(16, targetSentiment.getOffset()); }); }) ) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext( result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(42, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(34, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(24, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(26, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(18, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(8, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach( sentenceSentiment -> { assertEquals(27, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(19, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(9, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(17, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(25, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(17, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(7, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner( document -> StepVerifier.create(client.analyzeSentiment(document, null, new AnalyzeSentimentOptions().setIncludeOpinionMining(true))) .assertNext(result -> result.getSentences().forEach(sentenceSentiment -> { assertEquals(138, sentenceSentiment.getLength()); assertEquals(0, sentenceSentiment.getOffset()); sentenceSentiment.getOpinions().forEach(opinion -> { opinion.getAssessments().forEach(assessmentSentiment -> { assertEquals(7, assessmentSentiment.getLength()); assertEquals(130, assessmentSentiment.getOffset()); }); final TargetSentiment targetSentiment = opinion.getTarget(); assertEquals(5, targetSentiment.getLength()); assertEquals(120, targetSentiment.getOffset()); }); })) .verifyComplete(), SENTIMENT_OFFSET_INPUT ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareStringInputWithoutOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareStringInputRunner((documents, dummyOptions) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( false, getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareStringInputWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareStringInputRunner((documents, options) -> { boolean isValidApiVersionForDisplayName = serviceVersion != TextAnalyticsServiceVersion.V3_0 && serviceVersion != TextAnalyticsServiceVersion.V3_1; if (isValidApiVersionForDisplayName) { options.setDisplayName("operationName"); } SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<AnalyzeHealthcareEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); if (isValidApiVersionForDisplayName) { assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); } AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePageWithFhir(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareMaxOverload(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareLroRunner((documents, options) -> { boolean isValidApiVersionForDisplayName = serviceVersion != TextAnalyticsServiceVersion.V3_0 && serviceVersion != TextAnalyticsServiceVersion.V3_1; if (isValidApiVersionForDisplayName) { options.setDisplayName("operationName"); } SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<AnalyzeHealthcareEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); if (isValidApiVersionForDisplayName) { assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); } AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForSinglePage(), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareLroPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); healthcareLroPaginationRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); validateAnalyzeHealthcareEntitiesResultCollectionList( options.isIncludeStatistics(), getExpectedAnalyzeHealthcareEntitiesResultCollectionListForMultiplePages(0, 10, 0), analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList())); }, 10); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void healthcareLroEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyListRunner((documents, errorMessage) -> { StepVerifier.create(client.beginAnalyzeHealthcareEntities(documents, null)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && errorMessage.equals(throwable.getMessage())) .verify(); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils @Disabled("https: public void analyzeHealthcareEntitiesEmojiUnicodeCodePoint(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmoji(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiWithSkinToneModifierRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(22, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiFamily(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(29, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesEmojiFamilyWithSkinToneModifier(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emojiFamilyWithSkinToneModifierRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(37, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesDiacriticsNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfcRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(21, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesDiacriticsNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); diacriticsNfdRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(22, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesKoreanNfc(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfcRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesKoreanNfd(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); koreanNfdRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(20, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesZalgoText(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); zalgoTextRunner( document -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities( Collections.singletonList(new TextDocumentInput("0", document)), null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); analyzeHealthcareEntitiesPagedFlux.toStream().forEach(result -> result.forEach( entitiesResult -> entitiesResult.getEntities().forEach( entity -> { assertEquals(11, entity.getLength()); assertEquals(133, entity.getOffset()); }))); }, HEALTHCARE_ENTITY_OFFSET_INPUT); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareEntitiesForAssertion(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeHealthcareEntitiesForAssertionRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeHealthcareEntitiesPagedFlux analyzeHealthcareEntitiesPagedFlux = syncPoller.getFinalResult(); final HealthcareEntityAssertion assertion = analyzeHealthcareEntitiesPagedFlux.toStream().collect(Collectors.toList()) .get(0).stream().collect(Collectors.toList()) .get(0).getEntities().stream().collect(Collectors.toList()) .get(1) .getAssertion(); assertEquals(EntityConditionality.HYPOTHETICAL, assertion.getConditionality()); assertNull(assertion.getAssociation()); assertNull(assertion.getCertainty()); }); } @Disabled("Temporary disable it for green test") @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void cancelHealthcareLro(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); cancelHealthcareLroRunner((documents, options) -> { SyncPoller<AnalyzeHealthcareEntitiesOperationDetail, AnalyzeHealthcareEntitiesPagedFlux> syncPoller = client.beginAnalyzeHealthcareEntities(documents, options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.cancelOperation(); LongRunningOperationStatus operationStatus = syncPoller.poll().getStatus(); while (!LongRunningOperationStatus.USER_CANCELLED.equals(operationStatus)) { operationStatus = syncPoller.poll().getStatus(); } syncPoller.waitForCompletion(); Assertions.assertEquals(LongRunningOperationStatus.USER_CANCELLED, operationStatus); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsStringInputRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForActions(), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getRecognizePiiEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithOptions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchActionsRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollectionForActions(), null))), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getRecognizePiiEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getAnalyzeSentimentResultCollectionForActions(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithMultiSameKindActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsWithMultiSameKindActionsRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { assertEquals(2, actionsResult.getRecognizeEntitiesResults().stream().count()); assertEquals(2, actionsResult.getRecognizePiiEntitiesResults().stream().count()); assertEquals(2, actionsResult.getRecognizeLinkedEntitiesResults().stream().count()); assertEquals(2, actionsResult.getAnalyzeSentimentResults().stream().count()); assertEquals(2, actionsResult.getExtractKeyPhrasesResults().stream().count()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsWithActionNames(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsWithActionNamesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizeEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizePiiEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getRecognizeLinkedEntitiesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getAnalyzeSentimentResults().stream() .collect(Collectors.toList()).get(0).getActionName()); assertEquals(CUSTOM_ACTION_NAME, actionsResult.getExtractKeyPhrasesResults().stream() .collect(Collectors.toList()).get(0).getActionName()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsAutoDetectedLanguage(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeActionsAutoDetectedLanguageRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { List<RecognizeEntitiesResult> recognizeEntitiesResults = actionsResult.getRecognizeEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizeEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizeEntitiesResults.get(1).getDetectedLanguage()); List<RecognizePiiEntitiesResult> recognizePiiEntitiesResults = actionsResult.getRecognizePiiEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizePiiEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizePiiEntitiesResults.get(1).getDetectedLanguage()); List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResults = actionsResult.getRecognizeLinkedEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, recognizeLinkedEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, recognizeLinkedEntitiesResults.get(1).getDetectedLanguage()); List<AnalyzeSentimentResult> analyzeSentimentResults = actionsResult.getAnalyzeSentimentResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, analyzeSentimentResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, analyzeSentimentResults.get(1).getDetectedLanguage()); List<ExtractKeyPhraseResult> keyPhraseResults = actionsResult.getExtractKeyPhrasesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, keyPhraseResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, keyPhraseResults.get(1).getDetectedLanguage()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsAutoDetectedLanguageCustomTexts(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); analyzeActionsAutoDetectedLanguageCustomTextRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach(actionsResult -> { List<RecognizeEntitiesResult> customEntitiesResults = actionsResult.getRecognizeCustomEntitiesResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, customEntitiesResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, customEntitiesResults.get(1).getDetectedLanguage()); List<ClassifyDocumentResult> singleLabelResults = actionsResult.getSingleLabelClassifyResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, singleLabelResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, singleLabelResults.get(1).getDetectedLanguage()); List<ClassifyDocumentResult> multiLabelResults = actionsResult.getMultiLabelClassifyResults() .stream().collect(Collectors.toList()).get(0).getDocumentsResults() .stream().collect(Collectors.toList()); validatePrimaryLanguage(DETECTED_LANGUAGE_ENGLISH, multiLabelResults.get(0).getDetectedLanguage()); validatePrimaryLanguage(DETECTED_LANGUAGE_SPANISH, multiLabelResults.get(1).getDetectedLanguage()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsPagination(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeBatchActionsPaginationRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions( documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, getExpectedAnalyzeActionsResultListForMultiplePages(0, 20, 2), result.toStream().collect(Collectors.toList())); }, 22); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeActionsEmptyInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyListRunner((documents, errorMessage) -> StepVerifier.create(client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setRecognizeEntitiesActions(new RecognizeEntitiesAction()), null)) .expectErrorMatches(throwable -> throwable instanceof IllegalArgumentException && errorMessage.equals(throwable.getMessage())) .verify()); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeEntitiesRecognitionAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeEntitiesRecognitionRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(asList(getExpectedRecognizeEntitiesActionResult(false, null, TIME_NOW, getRecognizeEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeEntitiesRecognitionActionResolution(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeEntitiesRecognitionResolutionRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().forEach(actionsResult -> { actionsResult.getRecognizeEntitiesResults().forEach(nerActionResult -> { validateEntityResolutions(nerActionResult.getDocumentsResults()); }); }); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithCategoriesFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzePiiEntityRecognitionWithCategoriesFiltersRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForCategoriesFilter(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzePiiEntityRecognitionWithDomainFilters(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzePiiEntityRecognitionWithDomainFiltersRunner( (documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, Arrays.asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizePiiEntitiesActionResult(false, null, TIME_NOW, getExpectedBatchPiiEntitiesForDomainFilter(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); } ); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeLinkedEntityActions(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeLinkedEntityRecognitionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList( false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(asList(getExpectedRecognizeLinkedEntitiesActionResult(false, null, TIME_NOW, getRecognizeLinkedEntitiesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeKeyPhrasesExtractionAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractKeyPhrasesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedExtractKeyPhrasesActionResult(false, null, TIME_NOW, getExtractKeyPhrasesResultCollection(), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeSentimentAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeSentimentRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions().setIncludeStatistics(false)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedAnalyzeSentimentActionResult(false, null, TIME_NOW, getExpectedBatchTextSentiment(), null))), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeHealthcareAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); analyzeHealthcareEntitiesRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExpectedAnalyzeHealthcareEntitiesActionResult(false, null, TIME_NOW, getExpectedAnalyzeHealthcareEntitiesResultCollection(2, asList( getRecognizeHealthcareEntitiesResultWithFhir1("0"), getRecognizeHealthcareEntitiesResultWithFhir2())), null))), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntitiesAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getRecognizeCustomEntitiesResults().forEach( customEntitiesActionResult -> customEntitiesActionResult.getDocumentsResults().forEach( documentResult -> validateCategorizedEntities( documentResult.getEntities().stream().collect(Collectors.toList()))))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassificationAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleCategoryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getSingleLabelClassifyResults().forEach( customSingleCategoryActionResult -> customSingleCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateLabelClassificationResult(documentResult)))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiCategoryClassifyAction(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiCategoryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", null).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getMultiLabelClassifyResults().forEach( customMultiCategoryActionResult -> customMultiCategoryActionResult.getDocumentsResults().forEach( documentResult -> validateLabelClassificationResult(documentResult)))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntitiesStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesRunner((documents, parameters) -> { SyncPoller<RecognizeCustomEntitiesOperationDetail, RecognizeCustomEntitiesPagedFlux> syncPoller = client.beginRecognizeCustomEntities(documents, parameters.get(0), parameters.get(1)).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); RecognizeCustomEntitiesPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateCategorizedEntities(documentResult.getEntities().stream().collect(Collectors.toList())))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void recognizeCustomEntities(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); recognizeCustomEntitiesRunner((documents, parameters) -> { RecognizeCustomEntitiesOptions options = new RecognizeCustomEntitiesOptions() .setDisplayName("operationName"); SyncPoller<RecognizeCustomEntitiesOperationDetail, RecognizeCustomEntitiesPagedFlux> syncPoller = client.beginRecognizeCustomEntities(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<RecognizeCustomEntitiesOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); RecognizeCustomEntitiesPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateCategorizedEntities(documentResult.getEntities().stream().collect(Collectors.toList())))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassificationStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleLabelRunner((documents, parameters) -> { SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginSingleLabelClassify(documents, parameters.get(0), parameters.get(1)) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void singleLabelClassification(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomSingleLabelRunner((documents, parameters) -> { SingleLabelClassifyOptions options = new SingleLabelClassifyOptions().setDisplayName("operationName"); SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginSingleLabelClassify(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<ClassifyDocumentOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiLabelClassificationStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiLabelRunner((documents, parameters) -> { SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginMultiLabelClassify(documents, parameters.get(0), parameters.get(1)) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void multiLabelClassification(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, true); classifyCustomMultiLabelRunner((documents, parameters) -> { MultiLabelClassifyOptions options = new MultiLabelClassifyOptions().setDisplayName("operationName"); SyncPoller<ClassifyDocumentOperationDetail, ClassifyDocumentPagedFlux> syncPoller = client.beginMultiLabelClassify(documents, parameters.get(0), parameters.get(1), "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); PollResponse<ClassifyDocumentOperationDetail> pollResponse = syncPoller.waitForCompletion(); assertEquals(options.getDisplayName(), pollResponse.getValue().getDisplayName()); ClassifyDocumentPagedFlux pagedFlux = syncPoller.getFinalResult(); pagedFlux.toStream().collect(Collectors.toList()).forEach(resultCollection -> resultCollection.forEach(documentResult -> validateLabelClassificationResult(documentResult))); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getExtractSummaryActionResult(false, null, TIME_NOW, getExpectedExtractSummaryResultCollection(getExpectedExtractSummaryResultSortByOffset()), null))), IterableStream.of(null) )), result.toStream().collect(Collectors.toList())); }, null, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionSortedByOffset(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue(isAscendingOrderByOffSet( documentResult.getSentences().stream().collect(Collectors.toList())))))); }, 4, SummarySentencesOrder.OFFSET); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionSortedByRankScore(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue(isDescendingOrderByRankScore( documentResult.getSentences().stream().collect(Collectors.toList())))))); }, 4, SummarySentencesOrder.RANK); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithSentenceCountLessThanMaxCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertTrue( documentResult.getSentences().stream().collect(Collectors.toList()).size() < 20)))); }, 20, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionWithNonDefaultSentenceCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); final List<AnalyzeActionsResult> actionsResults = result.toStream().collect(Collectors.toList()); actionsResults.forEach( actionsResult -> actionsResult.getExtractSummaryResults().forEach( extractSummaryActionResult -> extractSummaryActionResult.getDocumentsResults().forEach( documentResult -> assertEquals( documentResult.getSentences().stream().collect(Collectors.toList()).size(), 5)))); }, 5, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeExtractSummaryActionMaxSentenceCountInvalidRangeException(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { extractSummaryActionRunner( (documents, tasks) -> { HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); }); assertEquals( TextAnalyticsErrorCode.INVALID_PARAMETER_VALUE, ((TextAnalyticsError) exception.getValue()).getErrorCode()); }, invalidCount, null); } } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void analyzeAbstractiveSummaryActionWithDefaultParameterValues(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryActionRunner((documents, tasks) -> { SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedFlux> syncPoller = client.beginAnalyzeActions(documents, tasks, "en", new AnalyzeActionsOptions()).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AnalyzeActionsResultPagedFlux result = syncPoller.getFinalResult(); validateAnalyzeBatchActionsResultList(false, false, asList(getExpectedAnalyzeBatchActionsResult( IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(null), IterableStream.of(asList(getAbstractSummaryActionResult(false, null, TIME_NOW, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), null ))) )), result.toStream().collect(Collectors.toList())); }, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryDuplicateIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); duplicateIdRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null)) .verifyErrorSatisfies(ex -> assertEquals(HttpResponseException.class, ex.getClass())); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryEmptyIdInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); emptyDocumentIdRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT, textAnalyticsError.getErrorCode()); }); }); } @Disabled("https: @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryTooManyDocuments(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); tooManyDocumentsRunner(inputs -> { StepVerifier.create(client.beginAbstractSummary(inputs, null, null)) .verifyErrorSatisfies(ex -> { final HttpResponseException httpResponseException = (HttpResponseException) ex; assertEquals(400, httpResponseException.getResponse().getStatusCode()); final TextAnalyticsError textAnalyticsError = (TextAnalyticsError) httpResponseException.getValue(); assertEquals(INVALID_DOCUMENT_BATCH, textAnalyticsError.getErrorCode()); }); }); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryStringInput(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryRunner((documents, options) -> { SyncPoller<AbstractSummaryOperationDetail, AbstractSummaryPagedFlux> syncPoller = client.beginAbstractSummary(documents) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AbstractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResult -> validateAbstractiveSummaryResultCollection(false, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), documentResult)); }, 4); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginAbstractSummaryMaxOverload(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); abstractSummaryMaxOverloadRunner((documents, options) -> { SyncPoller<AbstractSummaryOperationDetail, AbstractSummaryPagedFlux> syncPoller = client.beginAbstractSummary(documents, options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); AbstractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResult -> validateAbstractiveSummaryResultCollection(false, new AbstractSummaryResultCollection(asList(getExpectedAbstractiveSummaryResult())), documentResult)); }, 4); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySortedByOffset(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( isAscendingOrderByOffSet(documentResult.getSentences().stream().collect(Collectors.toList()))) )); }, 4, SummarySentencesOrder.OFFSET); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySortedByRankScore(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( isDescendingOrderByRankScore(documentResult.getSentences().stream().collect(Collectors.toList()))) )); }, 4, SummarySentencesOrder.RANK); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummarySentenceCountLessThanMaxCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertTrue( documentResult.getSentences().stream().collect(Collectors.toList()).size() < 20))); }, 20, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummaryNonDefaultSentenceCount(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); extractSummaryRunner((documents, options) -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options).getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); result.toStream().collect(Collectors.toList()).forEach( documentResultCollection -> documentResultCollection.forEach( documentResult -> assertEquals( documentResult.getSentences().stream().collect(Collectors.toList()).size(), 5))); }, 5, null); } @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("com.azure.ai.textanalytics.TestUtils public void beginExtractSummaryMaxSentenceCountInvalidRangeException(HttpClient httpClient, TextAnalyticsServiceVersion serviceVersion) { client = getTextAnalyticsAsyncClient(httpClient, serviceVersion, false); int[] invalidMaxSentenceCounts = {0, 21}; for (int invalidCount: invalidMaxSentenceCounts) { extractSummaryRunner( (documents, options) -> { HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { SyncPoller<ExtractSummaryOperationDetail, ExtractSummaryPagedFlux> syncPoller = client.beginExtractSummary(documents, "en", options) .getSyncPoller(); syncPoller = setPollInterval(syncPoller); syncPoller.waitForCompletion(); ExtractSummaryPagedFlux result = syncPoller.getFinalResult(); }); assertEquals( TextAnalyticsErrorCode.INVALID_PARAMETER_VALUE, ((TextAnalyticsError) exception.getValue()).getErrorCode()); }, invalidCount, null); } } }
Why do we do this at all?
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
charByte++;
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
Yea, this was a code that we might have copied from somewhere (may be .Net long time back), until Anu pointed out this issue when we did spot bugs check for v4 during its GA phase. Never really got the chance to fix it, until I started going over the github issues. It fixes this one - https://github.com/Azure/azure-sdk-for-java/issues/9104
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
charByte++;
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
But why do we add to the original value anyway?
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
charByte++;
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
Great question, I wish if I had an answer for it :) May be this history might help - https://msdata.visualstudio.com/CosmosDB/_git/CosmosDB?path=/Product/Microsoft.Azure.Documents/SharedFiles/Routing/StringPartitionKeyComponent.cs&version=GBmaster&line=94&lineEnd=95&lineStartColumn=1&lineEndColumn=1&lineStyle=plain&_a=contents Dates back to 2016 ;)
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
charByte++;
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
May be I can write some unit tests to see, will do so and will report back.
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
charByte++;
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
Here's the whole commit: https://msdata.visualstudio.com/CosmosDB/_git/CosmosDB/commit/71cfa1936b5dbd1f032b2028a6b1461c0401a74c?refName=refs/heads/master&path=/Product/Microsoft.Azure.Documents/SharedFiles/Routing/StringPartitionKeyComponent.cs&_a=compare Only thing I can guess is that the author wanted to avoid any embedded "0" bytes in the string, since it looks like the binary format being serialized into uses 0 as a terminator. Therefore it writes "byteVal+1", and the reads and subtracts 1.
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
charByte++;
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
Also looks like the C# version casts `char` directly to `byte`, and so won't handle any non-ascii strings :-/
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
charByte++;
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
Interesting, yeah for Java, UTF-8 encoding should handle that for us.
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
charByte++;
public void writeForBinaryEncoding(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); boolean shortString = this.utf8Value.length <= MAX_STRING_BYTES_TO_APPEND; for (int index = 0; index < (shortString ? this.utf8Value.length : MAX_STRING_BYTES_TO_APPEND + 1); index++) { byte charByte = this.utf8Value[index]; charByte++; outputStream.write(charByte); } if (shortString) { outputStream.write((byte) 0x00); } } catch (IOException e) { throw new IllegalStateException(e); } }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; public static final int MAX_STRING_BYTES_TO_APPEND = 100; private final String value; private final byte[] utf8Value; public StringPartitionKeyComponent(String value) { if (value == null) { throw new IllegalArgumentException("value"); } this.value = value; this.utf8Value = Utils.getUTF8Bytes(value); } @Override public int compareTo(IPartitionKeyComponent other) { StringPartitionKeyComponent otherString = Utils.as(other, StringPartitionKeyComponent.class) ; if (otherString == null) { throw new IllegalArgumentException("other"); } return this.value.compareTo(otherString.value); } @Override public int getTypeOrdinal() { return PartitionKeyComponentType.STRING.type; } @Override public int hashCode() { return value.hashCode(); } public IPartitionKeyComponent truncate() { if (this.value.length() > MAX_STRING_CHARS) { return new StringPartitionKeyComponent(this.value.substring(0, MAX_STRING_CHARS)); } return this; } @Override public void jsonEncode(JsonGenerator writer) { try { writer.writeString(this.value); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashing(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void writeForHashingV2(OutputStream outputStream) { try { outputStream.write((byte) PartitionKeyComponentType.STRING.type); outputStream.write(utf8Value); outputStream.write((byte) 0xFF); } catch (IOException e) { throw new IllegalStateException(e); } } @Override }
Isn't this the same logic as targetUser? Can we have a targetGroup method here?
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } TargetingFilterSettings settings = new TargetingFilterSettings(); Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Map<String, Map<String, Object>> exclusionMap = (Map<String, Map<String, Object>>) parameters .get(EXCLUSION); Map<String, Object> exclusionAsLists = new HashMap<>(); if (exclusionMap != null) { exclusionAsLists.put(USERS, exclusionMap.getOrDefault(USERS, new HashMap<String, Object>()).values()); exclusionAsLists.put(GROUPS, exclusionMap.getOrDefault(GROUPS, new HashMap<String, Object>()).values()); } parameters.put(EXCLUSION, exclusionAsLists); settings.setAudience(OBJECT_MAPPER.convertValue(parameters, Audience.class)); validateSettings(settings); Audience audience = settings.getAudience(); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, settings.getAudience().getDefaultRolloutPercentage()); }
}
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } TargetingFilterSettings settings = new TargetingFilterSettings(); Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Map<String, Map<String, Object>> exclusionMap = (Map<String, Map<String, Object>>) parameters .get(EXCLUSION); Map<String, Object> exclusionAsLists = new HashMap<>(); if (exclusionMap != null) { exclusionAsLists.put(USERS, exclusionMap.getOrDefault(USERS, new HashMap<String, Object>()).values()); exclusionAsLists.put(GROUPS, exclusionMap.getOrDefault(GROUPS, new HashMap<String, Object>()).values()); } parameters.put(EXCLUSION, exclusionAsLists); settings.setAudience(OBJECT_MAPPER.convertValue(parameters, Audience.class)); validateSettings(settings); Audience audience = settings.getAudience(); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { if (targetGroup(audience, targetingContext, context, group)) { return true; } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, settings.getAudience().getDefaultRolloutPercentage()); }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(TargetingFilterSettings settings) { String paramName = ""; String reason = ""; if (settings.getAudience() == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } Audience audience = settings.getAudience(); if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean targetGroup(Audience audience, TargetingFilterContext targetingContext, FeatureFilterEvaluationContext context, String group) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } return false; } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(TargetingFilterSettings settings) { String paramName = ""; String reason = ""; if (settings.getAudience() == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } Audience audience = settings.getAudience(); if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
Users 100% get a feature. A percentage of a group can get a feature. i.e Ring1 users get it 95% of the time and Ring2 users get it 25% of the time.
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } TargetingFilterSettings settings = new TargetingFilterSettings(); Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Map<String, Map<String, Object>> exclusionMap = (Map<String, Map<String, Object>>) parameters .get(EXCLUSION); Map<String, Object> exclusionAsLists = new HashMap<>(); if (exclusionMap != null) { exclusionAsLists.put(USERS, exclusionMap.getOrDefault(USERS, new HashMap<String, Object>()).values()); exclusionAsLists.put(GROUPS, exclusionMap.getOrDefault(GROUPS, new HashMap<String, Object>()).values()); } parameters.put(EXCLUSION, exclusionAsLists); settings.setAudience(OBJECT_MAPPER.convertValue(parameters, Audience.class)); validateSettings(settings); Audience audience = settings.getAudience(); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, settings.getAudience().getDefaultRolloutPercentage()); }
}
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } TargetingFilterSettings settings = new TargetingFilterSettings(); Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Map<String, Map<String, Object>> exclusionMap = (Map<String, Map<String, Object>>) parameters .get(EXCLUSION); Map<String, Object> exclusionAsLists = new HashMap<>(); if (exclusionMap != null) { exclusionAsLists.put(USERS, exclusionMap.getOrDefault(USERS, new HashMap<String, Object>()).values()); exclusionAsLists.put(GROUPS, exclusionMap.getOrDefault(GROUPS, new HashMap<String, Object>()).values()); } parameters.put(EXCLUSION, exclusionAsLists); settings.setAudience(OBJECT_MAPPER.convertValue(parameters, Audience.class)); validateSettings(settings); Audience audience = settings.getAudience(); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { if (targetGroup(audience, targetingContext, context, group)) { return true; } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, settings.getAudience().getDefaultRolloutPercentage()); }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(TargetingFilterSettings settings) { String paramName = ""; String reason = ""; if (settings.getAudience() == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } Audience audience = settings.getAudience(); if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean targetGroup(Audience audience, TargetingFilterContext targetingContext, FeatureFilterEvaluationContext context, String group) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } return false; } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(TargetingFilterSettings settings) { String paramName = ""; String reason = ""; if (settings.getAudience() == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } Audience audience = settings.getAudience(); if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
ok, so that's the findFirst. But can we still extract this into a method?
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } TargetingFilterSettings settings = new TargetingFilterSettings(); Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Map<String, Map<String, Object>> exclusionMap = (Map<String, Map<String, Object>>) parameters .get(EXCLUSION); Map<String, Object> exclusionAsLists = new HashMap<>(); if (exclusionMap != null) { exclusionAsLists.put(USERS, exclusionMap.getOrDefault(USERS, new HashMap<String, Object>()).values()); exclusionAsLists.put(GROUPS, exclusionMap.getOrDefault(GROUPS, new HashMap<String, Object>()).values()); } parameters.put(EXCLUSION, exclusionAsLists); settings.setAudience(OBJECT_MAPPER.convertValue(parameters, Audience.class)); validateSettings(settings); Audience audience = settings.getAudience(); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, settings.getAudience().getDefaultRolloutPercentage()); }
}
public boolean evaluate(FeatureFilterEvaluationContext context) { if (context == null) { throw new IllegalArgumentException("Targeting Context not configured."); } TargetingFilterContext targetingContext = new TargetingFilterContext(); contextAccessor.configureTargetingContext(targetingContext); if (validateTargetingContext(targetingContext)) { LOGGER.warn("No targeting context available for targeting evaluation."); return false; } TargetingFilterSettings settings = new TargetingFilterSettings(); Map<String, Object> parameters = context.getParameters(); Object audienceObject = parameters.get(AUDIENCE); if (audienceObject != null) { parameters = (Map<String, Object>) audienceObject; } updateValueFromMapToList(parameters, USERS); updateValueFromMapToList(parameters, GROUPS); Map<String, Map<String, Object>> exclusionMap = (Map<String, Map<String, Object>>) parameters .get(EXCLUSION); Map<String, Object> exclusionAsLists = new HashMap<>(); if (exclusionMap != null) { exclusionAsLists.put(USERS, exclusionMap.getOrDefault(USERS, new HashMap<String, Object>()).values()); exclusionAsLists.put(GROUPS, exclusionMap.getOrDefault(GROUPS, new HashMap<String, Object>()).values()); } parameters.put(EXCLUSION, exclusionAsLists); settings.setAudience(OBJECT_MAPPER.convertValue(parameters, Audience.class)); validateSettings(settings); Audience audience = settings.getAudience(); if (targetUser(targetingContext.getUserId(), audience.getExclusion().getUsers())) { return false; } if (targetingContext.getGroups() != null && audience.getExclusion().getGroups() != null) { for (String group : targetingContext.getGroups()) { Optional<String> groupRollout = audience.getExclusion().getGroups().stream() .filter(g -> equals(g, group)).findFirst(); if (groupRollout.isPresent()) { return false; } } } if (targetUser(targetingContext.getUserId(), audience.getUsers())) { return true; } if (targetingContext.getGroups() != null && audience.getGroups() != null) { for (String group : targetingContext.getGroups()) { if (targetGroup(audience, targetingContext, context, group)) { return true; } } } String defaultContextId = targetingContext.getUserId() + "\n" + context.getFeatureName(); return isTargeted(defaultContextId, settings.getAudience().getDefaultRolloutPercentage()); }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(TargetingFilterSettings settings) { String paramName = ""; String reason = ""; if (settings.getAudience() == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } Audience audience = settings.getAudience(); if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
class TargetingFilter implements FeatureFilter { private static final Logger LOGGER = LoggerFactory.getLogger(TargetingFilter.class); /** * users field in the filter */ protected static final String USERS = "users"; /** * groups field in the filter */ protected static final String GROUPS = "groups"; /** * Audience in the filter */ protected static final String AUDIENCE = "Audience"; /** * Audience that always returns false */ protected static final String EXCLUSION = "exclusion"; /** * Error message for when the total Audience value is greater than 100 percent. */ protected static final String OUT_OF_RANGE = "The value is out of the accepted range."; private static final String REQUIRED_PARAMETER = "Value cannot be null."; /** * Object Mapper for converting configurations to features */ protected static final ObjectMapper OBJECT_MAPPER = JsonMapper.builder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true).build(); /** * Accessor for identifying the current user/group when evaluating */ protected final TargetingContextAccessor contextAccessor; /** * Options for evaluating the filter */ protected final TargetingEvaluationOptions options; /** * Filter for targeting a user/group/percentage of users. * * @param contextAccessor Accessor for identifying the current user/group when evaluating */ public TargetingFilter(TargetingContextAccessor contextAccessor) { this.contextAccessor = contextAccessor; this.options = new TargetingEvaluationOptions(); } /** * `Microsoft.TargetingFilter` evaluates a user/group/overall rollout of a feature. * * @param contextAccessor Context for evaluating the users/groups. * @param options enables customization of the filter. */ public TargetingFilter(TargetingContextAccessor contextAccessor, TargetingEvaluationOptions options) { this.contextAccessor = contextAccessor; this.options = options; } @Override @SuppressWarnings("unchecked") private boolean targetUser(String userId, List<String> users) { return userId != null && users != null && users.stream().anyMatch(user -> equals(userId, user)); } private boolean targetGroup(Audience audience, TargetingFilterContext targetingContext, FeatureFilterEvaluationContext context, String group) { Optional<GroupRollout> groupRollout = audience.getGroups().stream() .filter(g -> equals(g.getName(), group)).findFirst(); if (groupRollout.isPresent()) { String audienceContextId = targetingContext.getUserId() + "\n" + context.getName() + "\n" + group; if (isTargeted(audienceContextId, groupRollout.get().getRolloutPercentage())) { return true; } } return false; } private boolean validateTargetingContext(TargetingFilterContext targetingContext) { boolean hasUserDefined = StringUtils.hasText(targetingContext.getUserId()); boolean hasGroupsDefined = targetingContext.getGroups() != null; boolean hasAtLeastOneGroup = false; if (hasGroupsDefined) { hasAtLeastOneGroup = targetingContext.getGroups().stream().anyMatch(group -> StringUtils.hasText(group)); } return (!hasUserDefined && !(hasGroupsDefined && hasAtLeastOneGroup)); } /** * Computes the percentage that the contextId falls into. * * @param contextId Id of the context being targeted * @return the bucket value of the context id * @throws TargetingException Unable to create hash of target context */ protected double isTargetedPercentage(String contextId) { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); hash = digest.digest(contextId.getBytes(Charset.defaultCharset())); } catch (NoSuchAlgorithmException e) { throw new TargetingException("Unable to find SHA-256 for targeting.", e); } if (hash == null) { throw new TargetingException("Unable to create Targeting Hash for " + contextId); } ByteBuffer wrapped = ByteBuffer.wrap(hash); int contextMarker = Math.abs(wrapped.getInt()); return (contextMarker / (double) Integer.MAX_VALUE) * 100; } private boolean isTargeted(String contextId, double percentage) { return isTargetedPercentage(contextId) < percentage; } /** * Validates the settings of a targeting filter. * * @param settings targeting filter settings * @throws TargetingException when a required parameter is missing or percentage value is greater than 100. */ void validateSettings(TargetingFilterSettings settings) { String paramName = ""; String reason = ""; if (settings.getAudience() == null) { paramName = AUDIENCE; reason = REQUIRED_PARAMETER; throw new TargetingException(paramName + " : " + reason); } Audience audience = settings.getAudience(); if (audience.getDefaultRolloutPercentage() < 0 || audience.getDefaultRolloutPercentage() > 100) { paramName = AUDIENCE + "." + audience.getDefaultRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } List<GroupRollout> groups = audience.getGroups(); if (groups != null) { for (int index = 0; index < groups.size(); index++) { GroupRollout groupRollout = groups.get(index); if (groupRollout.getRolloutPercentage() < 0 || groupRollout.getRolloutPercentage() > 100) { paramName = AUDIENCE + "[" + index + "]." + groups.get(index).getRolloutPercentage(); reason = OUT_OF_RANGE; throw new TargetingException(paramName + " : " + reason); } } } } /** * Checks if two strings are equal, ignores case if configured to. * * @param s1 string to compare * @param s2 string to compare * @return true if the strings are equal */ private boolean equals(String s1, String s2) { if (options.isIgnoreCase()) { return s1.equalsIgnoreCase(s2); } return s1.equals(s2); } /** * Looks at the given key in the parameters and coverts it to a list if it is currently a map. Used for updating * fields in the targeting filter. * * @param <T> Type of object inside of parameters for the given key * @param parameters map of generic objects * @param key key of object int the parameters map */ @SuppressWarnings("unchecked") private void updateValueFromMapToList(Map<String, Object> parameters, String key) { Object objectMap = parameters.get(key); if (objectMap instanceof Map) { Collection<Object> toType = ((Map<String, Object>) objectMap).values(); parameters.put(key, toType); } } }
NIT: should we share the same "date"
void setAuthorizationHeaders(HttpRequest httpRequest) { BinaryData binaryData = httpRequest.getBodyAsBinaryData(); final ByteBuffer byteBuffer = binaryData == null ? EMPTY_BYTE_BUFFER : binaryData.toByteBuffer(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); Mac sha256HMAC = Mac.getInstance("HmacSHA256"); sha256HMAC.init(new SecretKeySpec(credentials.secret(), "HmacSHA256")); messageDigest.update(byteBuffer.duplicate()); String contentHash = Base64.getEncoder().encodeToString(messageDigest.digest()); URL url = httpRequest.getUrl(); String pathAndQuery = url.getPath(); if (url.getQuery() != null) { pathAndQuery += '?' + url.getQuery(); } HttpHeaders headers = httpRequest.getHeaders(); String date = headers.getValue(HttpHeaderName.DATE); if (date == null) { date = DateTimeRfc1123.toRfc1123String(OffsetDateTime.now(ZoneOffset.UTC)); headers.set(HttpHeaderName.DATE, date); } String signed = url.getHost() + ";" + headers.getValue(HttpHeaderName.DATE) + ";" + contentHash; headers.set(HttpHeaderName.HOST, url.getHost()) .set(X_MS_CONTENT_SHA256, contentHash); String stringToSign = httpRequest.getHttpMethod().toString().toUpperCase(Locale.US) + "\n" + pathAndQuery + "\n" + signed; String signature = Base64.getEncoder() .encodeToString(sha256HMAC.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))); headers.set(HttpHeaderName.AUTHORIZATION, "HMAC-SHA256 Credential=" + credentials.id() + "&SignedHeaders=Host;Date;x-ms-content-sha256&Signature=" + signature); } catch (GeneralSecurityException e) { throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } }
String signed = url.getHost() + ";" + headers.getValue(HttpHeaderName.DATE) + ";" + contentHash;
void setAuthorizationHeaders(HttpRequest httpRequest) { BinaryData binaryData = httpRequest.getBodyAsBinaryData(); final ByteBuffer byteBuffer = binaryData == null ? EMPTY_BYTE_BUFFER : binaryData.toByteBuffer(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); Mac sha256HMAC = Mac.getInstance("HmacSHA256"); sha256HMAC.init(new SecretKeySpec(credentials.secret(), "HmacSHA256")); messageDigest.update(byteBuffer.duplicate()); String contentHash = Base64.getEncoder().encodeToString(messageDigest.digest()); URL url = httpRequest.getUrl(); String pathAndQuery = url.getPath(); if (url.getQuery() != null) { pathAndQuery += '?' + url.getQuery(); } HttpHeaders headers = httpRequest.getHeaders(); String date = headers.getValue(HttpHeaderName.DATE); if (date == null) { date = DateTimeRfc1123.toRfc1123String(OffsetDateTime.now(ZoneOffset.UTC)); headers.set(HttpHeaderName.DATE, date); } String signed = url.getHost() + ";" + date + ";" + contentHash; headers.set(HttpHeaderName.HOST, url.getHost()) .set(X_MS_CONTENT_SHA256, contentHash); String stringToSign = httpRequest.getHttpMethod().toString().toUpperCase(Locale.US) + "\n" + pathAndQuery + "\n" + signed; String signature = Base64.getEncoder() .encodeToString(sha256HMAC.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))); headers.set(HttpHeaderName.AUTHORIZATION, "HMAC-SHA256 Credential=" + credentials.id() + "&SignedHeaders=Host;Date;x-ms-content-sha256&Signature=" + signature); } catch (GeneralSecurityException e) { throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } }
class ConfigurationClientCredentials { private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientCredentials.class); private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocate(0); static final HttpHeaderName X_MS_CONTENT_SHA256 = HttpHeaderName.fromString("x-ms-content-sha256"); private final CredentialInformation credentials; /** * Creates an instance that is able to authorize requests to Azure App Configuration service. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" */ public ConfigurationClientCredentials(String connectionString) { credentials = new CredentialInformation(connectionString); } /** * Gets the base URI of the Azure App Configuration instance based on the provided connection string. * * @return The base url of the configuration service extracted from connection string provided. */ public String getBaseUri() { return this.credentials.baseUri().toString(); } /** * Sets the {@code Authorization} header on the request. * * @param httpRequest The request being authenticated. */ private static class CredentialInformation { private static final String ENDPOINT = "endpoint="; private static final String ID = "id="; private static final String SECRET = SECRET_PLACEHOLDER; private final URL baseUri; private final String id; private final byte[] secret; URL baseUri() { return baseUri; } String id() { return id; } byte[] secret() { return secret; } CredentialInformation(String connectionString) { if (CoreUtils.isNullOrEmpty(connectionString)) { throw new IllegalArgumentException("'connectionString' cannot be null or empty."); } String[] args = connectionString.split(";"); if (args.length < 3) { throw new IllegalArgumentException("invalid connection string segment count"); } URL baseUri = null; String id = null; byte[] secret = null; for (String arg : args) { String segment = arg.trim(); if (ENDPOINT.regionMatches(true, 0, segment, 0, ENDPOINT.length())) { try { baseUri = new URL(segment.substring(ENDPOINT.length())); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } else if (ID.regionMatches(true, 0, segment, 0, ID.length())) { id = segment.substring(ID.length()); } else if (SECRET.regionMatches(true, 0, segment, 0, SECRET.length())) { String secretBase64 = segment.substring(SECRET.length()); secret = Base64.getDecoder().decode(secretBase64); } } this.baseUri = baseUri; this.id = id; this.secret = secret; if (this.baseUri == null || CoreUtils.isNullOrEmpty(this.id) || this.secret == null || this.secret.length == 0) { throw new IllegalArgumentException("Could not parse 'connectionString'." + " Expected format: 'endpoint={endpoint};id={id};secret={secret}'. Actual:" + connectionString); } } } }
class ConfigurationClientCredentials { private static final ClientLogger LOGGER = new ClientLogger(ConfigurationClientCredentials.class); private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocate(0); static final HttpHeaderName X_MS_CONTENT_SHA256 = HttpHeaderName.fromString("x-ms-content-sha256"); private final CredentialInformation credentials; /** * Creates an instance that is able to authorize requests to Azure App Configuration service. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" */ public ConfigurationClientCredentials(String connectionString) { credentials = new CredentialInformation(connectionString); } /** * Gets the base URI of the Azure App Configuration instance based on the provided connection string. * * @return The base url of the configuration service extracted from connection string provided. */ public String getBaseUri() { return this.credentials.baseUri().toString(); } /** * Sets the {@code Authorization} header on the request. * * @param httpRequest The request being authenticated. */ private static class CredentialInformation { private static final String ENDPOINT = "endpoint="; private static final String ID = "id="; private static final String SECRET = SECRET_PLACEHOLDER; private final URL baseUri; private final String id; private final byte[] secret; URL baseUri() { return baseUri; } String id() { return id; } byte[] secret() { return secret; } CredentialInformation(String connectionString) { if (CoreUtils.isNullOrEmpty(connectionString)) { throw new IllegalArgumentException("'connectionString' cannot be null or empty."); } String[] args = connectionString.split(";"); if (args.length < 3) { throw new IllegalArgumentException("invalid connection string segment count"); } URL baseUri = null; String id = null; byte[] secret = null; for (String arg : args) { String segment = arg.trim(); if (ENDPOINT.regionMatches(true, 0, segment, 0, ENDPOINT.length())) { try { baseUri = new URL(segment.substring(ENDPOINT.length())); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } else if (ID.regionMatches(true, 0, segment, 0, ID.length())) { id = segment.substring(ID.length()); } else if (SECRET.regionMatches(true, 0, segment, 0, SECRET.length())) { String secretBase64 = segment.substring(SECRET.length()); secret = Base64.getDecoder().decode(secretBase64); } } this.baseUri = baseUri; this.id = id; this.secret = secret; if (this.baseUri == null || CoreUtils.isNullOrEmpty(this.id) || this.secret == null || this.secret.length == 0) { throw new IllegalArgumentException("Could not parse 'connectionString'." + " Expected format: 'endpoint={endpoint};id={id};secret={secret}'. Actual:" + connectionString); } } } }
nit: your indentation is shifted.
Mono<Response<Void>> sendDtmfWithResponseInternal(CommunicationIdentifier targetParticipant, List<DtmfTone> tones, String operationContext, Context context) { try { context = context == null ? Context.NONE : context; SendDtmfRequestInternal requestInternal = new SendDtmfRequestInternal() .setTargetParticipant(CommunicationIdentifierConverter.convert(targetParticipant)) .setTones(tones.stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList())) .setOperationContext(operationContext); return contentsInternal.sendDtmfWithResponseAsync(callConnectionId, requestInternal, context); } catch (RuntimeException e) { return monoError(logger, e); } }
.setOperationContext(operationContext);
new SendDtmfRequestInternal() .setTargetParticipant(CommunicationIdentifierConverter.convert(targetParticipant)) .setTones(tones.stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList())) .setOperationContext(operationContext); return contentsInternal.sendDtmfWithResponseAsync(callConnectionId, requestInternal, context); } catch (RuntimeException e) { return monoError(logger, e); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOrDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechOrDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUrl()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechOrDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOrDtmfOptions speechOrDtmfRecognizeOptions = (CallMediaRecognizeSpeechOrDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) speechOrDtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (speechOrDtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(speechOrDtmfRecognizeOptions.getMaxTonesToCollect()); } if (speechOrDtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = speechOrDtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechOrDtmfRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(speechOrDtmfRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechOrDtmfRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechOrDtmfRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechOrDtmfRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechOrDtmfRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } /** * Send DTMF tones * @param targetParticipant the target participant * @param tones tones to be sent * @return Response for successful sendDtmf request. */ public Mono<Void> sendDtmf(CommunicationIdentifier targetParticipant, List<DtmfTone> tones) { return sendDtmfWithResponse(targetParticipant, tones, null).then(); } /** * Send DTMF tones * @param targetParticipant the target participant * @param tones tones to be sent * @param operationContext operationContext (pass null if not applicable) * @return Response for successful sendDtmf request. */ public Mono<Response<Void>> sendDtmfWithResponse(CommunicationIdentifier targetParticipant, List<DtmfTone> tones, String operationContext) { return withContext(context -> sendDtmfWithResponseInternal(targetParticipant, tones, operationContext, context)); } Mono<Response<Void>> sendDtmfWithResponseInternal(CommunicationIdentifier targetParticipant, List<DtmfTone> tones, String operationContext, Context context) { try { context = context == null ? Context.NONE : context; SendDtmfRequestInternal requestInternal = } /** * Starts continuous Dtmf recognition. * * @param targetParticipant the target participant * @return void */ public Mono<Void> startContinuousDtmfRecognition(CommunicationIdentifier targetParticipant) { return startContinuousDtmfRecognitionWithResponse(targetParticipant, null).then(); } /** * Starts continuous Dtmf recognition. * @param targetParticipant the target participant * @param operationContext operationContext (pass null if not applicable) * @return Response for successful start continuous dtmf recognition request. */ public Mono<Response<Void>> startContinuousDtmfRecognitionWithResponse(CommunicationIdentifier targetParticipant, String operationContext) { return withContext(context -> startContinuousDtmfRecognitionWithResponseInternal(targetParticipant, operationContext, context)); } Mono<Response<Void>> startContinuousDtmfRecognitionWithResponseInternal(CommunicationIdentifier targetParticipant, String operationContext, Context context) { try { context = context == null ? Context.NONE : context; ContinuousDtmfRecognitionRequestInternal requestInternal = new ContinuousDtmfRecognitionRequestInternal() .setTargetParticipant(CommunicationIdentifierConverter.convert(targetParticipant)) .setOperationContext(operationContext); return contentsInternal.startContinuousDtmfRecognitionWithResponseAsync(callConnectionId, requestInternal, context); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Stops continuous Dtmf recognition. * @param targetParticipant the target participant * @return void */ public Mono<Void> stopContinuousDtmfRecognition(CommunicationIdentifier targetParticipant) { return stopContinuousDtmfRecognitionWithResponse(targetParticipant, null).then(); } /** * Stops continuous Dtmf recognition. * @param targetParticipant the target participant * @param operationContext operationContext (pass null if not applicable) * @return Response for successful stop continuous dtmf recognition request. */ public Mono<Response<Void>> stopContinuousDtmfRecognitionWithResponse(CommunicationIdentifier targetParticipant, String operationContext) { return withContext(context -> stopContinuousDtmfRecognitionWithResponseInternal(targetParticipant, operationContext, context)); } Mono<Response<Void>> stopContinuousDtmfRecognitionWithResponseInternal(CommunicationIdentifier targetParticipant, String operationContext, Context context) { try { context = context == null ? Context.NONE : context; ContinuousDtmfRecognitionRequestInternal requestInternal = new ContinuousDtmfRecognitionRequestInternal() .setTargetParticipant(CommunicationIdentifierConverter.convert(targetParticipant)) .setOperationContext(operationContext); return contentsInternal.stopContinuousDtmfRecognitionWithResponseAsync(callConnectionId, requestInternal, context); } catch (RuntimeException e) { return monoError(logger, e); } } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws HttpResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOrDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechOrDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUrl()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechOrDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOrDtmfOptions speechOrDtmfRecognizeOptions = (CallMediaRecognizeSpeechOrDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) speechOrDtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (speechOrDtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(speechOrDtmfRecognizeOptions.getMaxTonesToCollect()); } if (speechOrDtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = speechOrDtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechOrDtmfRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(speechOrDtmfRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechOrDtmfRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechOrDtmfRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechOrDtmfRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechOrDtmfRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } /** * Send DTMF tones * @param targetParticipant the target participant * @param tones tones to be sent * @return Response for successful sendDtmf request. */ public Mono<Void> sendDtmf(CommunicationIdentifier targetParticipant, List<DtmfTone> tones) { return sendDtmfWithResponse(targetParticipant, tones, null).then(); } /** * Send DTMF tones * @param targetParticipant the target participant * @param tones tones to be sent * @param operationContext operationContext (pass null if not applicable) * @return Response for successful sendDtmf request. */ public Mono<Response<Void>> sendDtmfWithResponse(CommunicationIdentifier targetParticipant, List<DtmfTone> tones, String operationContext) { return withContext(context -> sendDtmfWithResponseInternal(targetParticipant, tones, operationContext, context)); } Mono<Response<Void>> sendDtmfWithResponseInternal(CommunicationIdentifier targetParticipant, List<DtmfTone> tones, String operationContext, Context context) { try { context = context == null ? Context.NONE : context; SendDtmfRequestInternal requestInternal = } /** * Starts continuous Dtmf recognition. * * @param targetParticipant the target participant * @return void */ public Mono<Void> startContinuousDtmfRecognition(CommunicationIdentifier targetParticipant) { return startContinuousDtmfRecognitionWithResponse(targetParticipant, null).then(); } /** * Starts continuous Dtmf recognition. * @param targetParticipant the target participant * @param operationContext operationContext (pass null if not applicable) * @return Response for successful start continuous dtmf recognition request. */ public Mono<Response<Void>> startContinuousDtmfRecognitionWithResponse(CommunicationIdentifier targetParticipant, String operationContext) { return withContext(context -> startContinuousDtmfRecognitionWithResponseInternal(targetParticipant, operationContext, context)); } Mono<Response<Void>> startContinuousDtmfRecognitionWithResponseInternal(CommunicationIdentifier targetParticipant, String operationContext, Context context) { try { context = context == null ? Context.NONE : context; ContinuousDtmfRecognitionRequestInternal requestInternal = new ContinuousDtmfRecognitionRequestInternal() .setTargetParticipant(CommunicationIdentifierConverter.convert(targetParticipant)) .setOperationContext(operationContext); return contentsInternal.startContinuousDtmfRecognitionWithResponseAsync(callConnectionId, requestInternal, context); } catch (RuntimeException e) { return monoError(logger, e); } } /** * Stops continuous Dtmf recognition. * @param targetParticipant the target participant * @return void */ public Mono<Void> stopContinuousDtmfRecognition(CommunicationIdentifier targetParticipant) { return stopContinuousDtmfRecognitionWithResponse(targetParticipant, null).then(); } /** * Stops continuous Dtmf recognition. * @param targetParticipant the target participant * @param operationContext operationContext (pass null if not applicable) * @return Response for successful stop continuous dtmf recognition request. */ public Mono<Response<Void>> stopContinuousDtmfRecognitionWithResponse(CommunicationIdentifier targetParticipant, String operationContext) { return withContext(context -> stopContinuousDtmfRecognitionWithResponseInternal(targetParticipant, operationContext, context)); } Mono<Response<Void>> stopContinuousDtmfRecognitionWithResponseInternal(CommunicationIdentifier targetParticipant, String operationContext, Context context) { try { context = context == null ? Context.NONE : context; ContinuousDtmfRecognitionRequestInternal requestInternal = new ContinuousDtmfRecognitionRequestInternal() .setTargetParticipant(CommunicationIdentifierConverter.convert(targetParticipant)) .setOperationContext(operationContext); return contentsInternal.stopContinuousDtmfRecognitionWithResponseAsync(callConnectionId, requestInternal, context); } catch (RuntimeException e) { return monoError(logger, e); } } }
is this the only attribute SpeechOptionsInternal has?
Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } }
SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs());
new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
I wonder if this indentation is wrong or just the way Git presents it is wrong.
Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } }
.setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant()));
new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
I think that `convert` is a better word than `translate`. Even `getPlaySourceInternal` may work better.
Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } }
playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource);
new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
I like this approach to get the `playSourceInternal` variable. We should replicate it for `RecognizeRequest` (line 236) to stop that method from growing.
PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); }
playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource);
PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
this should be SSML.
private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; }
.setSourceType(PlaySourceTypeInternal.TEXT)
private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
correct, changed to SSML
private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; }
.setSourceType(PlaySourceTypeInternal.TEXT)
private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
yes, refactored the recognizeRequest methods
PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); }
playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource);
PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
changed to convert
Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } }
playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource);
new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
the indentation is checked through java checkstyle, which should be fine
Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } }
.setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant()));
new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
yes, SpeechOptionsInternal is autogenerated
Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); } if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } }
SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs());
new DtmfOptionsInternal(); dtmfOptionsInternal.setInterToneTimeoutInSeconds((int) dtmfRecognizeOptions.getInterToneTimeout().getSeconds()); if (dtmfRecognizeOptions.getMaxTonesToCollect() != null) { dtmfOptionsInternal.setMaxTonesToCollect(dtmfRecognizeOptions.getMaxTonesToCollect()); }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::translateDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(translateListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = translatePlaySourceToPlaySourceInternal(playSource); } RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal translatePlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> translateListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::translateRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal translateRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(translateDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal translateDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } }
class CallMediaAsync { private final CallMediasImpl contentsInternal; private final String callConnectionId; private final ClientLogger logger; CallMediaAsync(String callConnectionId, CallMediasImpl contentsInternal) { this.callConnectionId = callConnectionId; this.contentsInternal = contentsInternal; this.logger = new ClientLogger(CallMediaAsync.class); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful play request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> play(PlaySource playSource, List<CommunicationIdentifier> playTo) { return playWithResponse(playSource, playTo, null).flatMap(FluxUtil::toMono); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return Void for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> playToAll(PlaySource playSource) { return playToAllWithResponse(playSource, null).flatMap(FluxUtil::toMono); } /** * Play * * @param playSource A {@link PlaySource} representing the source to play. * @param playTo the targets to play to * @param options play options. * @return Response for successful play request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playWithResponse(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { return playWithResponseInternal(playSource, playTo, options, null); } /** * Play to all participants * * @param playSource A {@link PlaySource} representing the source to play. * @param options play options. * @return Response for successful playAll request. * @throws CallingServerErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> playToAllWithResponse(PlaySource playSource, PlayOptions options) { return playWithResponseInternal(playSource, Collections.emptyList(), options, null); } /** * Recognize operation. * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Void> startRecognizing(CallMediaRecognizeOptions recognizeOptions) { return startRecognizingWithResponse(recognizeOptions).then(); } /** * Recognize operation * @param recognizeOptions Different attributes for recognize. * @return Response for successful recognize request. */ public Mono<Response<Void>> startRecognizingWithResponse(CallMediaRecognizeOptions recognizeOptions) { return withContext(context -> recognizeWithResponseInternal(recognizeOptions, context)); } Mono<Response<Void>> recognizeWithResponseInternal(CallMediaRecognizeOptions recognizeOptions, Context context) { try { context = context == null ? Context.NONE : context; if (recognizeOptions instanceof CallMediaRecognizeDtmfOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromDtmfConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeChoiceOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromChoiceConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else if (recognizeOptions instanceof CallMediaRecognizeSpeechOptions) { RecognizeRequest recognizeRequest = getRecognizeRequestFromSpeechConfiguration(recognizeOptions); return contentsInternal.recognizeWithResponseAsync(callConnectionId, recognizeRequest, context); } else { return monoError(logger, new UnsupportedOperationException(recognizeOptions.getClass().getName())); } } catch (RuntimeException e) { return monoError(logger, e); } } /** * Cancels all the queued media operations. * @return Void */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> cancelAllMediaOperations() { return cancelAllMediaOperationsWithResponse().then(); } /** * Cancels all the queued media operations * @return Response for successful playAll request. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> cancelAllMediaOperationsWithResponse() { return cancelAllMediaOperationsWithResponseInternal(null); } Mono<Response<Void>> cancelAllMediaOperationsWithResponseInternal(Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; return contentsInternal.cancelAllMediaOperationsWithResponseAsync(callConnectionId, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } Mono<Response<Void>> playWithResponseInternal(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options, Context context) { try { return withContext(contextValue -> { contextValue = context == null ? contextValue : context; PlayRequest request = getPlayRequest(playSource, playTo, options); return contentsInternal.playWithResponseAsync(callConnectionId, request, contextValue) .onErrorMap(HttpResponseException.class, ErrorConstructorProxy::create); }); } catch (RuntimeException ex) { return monoError(logger, ex); } } PlayRequest getPlayRequest(PlaySource playSource, List<CommunicationIdentifier> playTo, PlayOptions options) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } else if (playSource instanceof SsmlSource) { playSourceInternal = getPlaySourceInternalFromSsmlSource((SsmlSource) playSource); } if (playSourceInternal.getSourceType() != null) { PlayRequest request = new PlayRequest() .setPlaySourceInfo(playSourceInternal) .setPlayTo( playTo .stream() .map(CommunicationIdentifierConverter::convert) .collect(Collectors.toList())); if (options != null) { request.setPlayOptions(new PlayOptionsInternal().setLoop(options.isLoop())); request.setOperationContext(options.getOperationContext()); } return request; } throw logger.logExceptionAsError(new IllegalArgumentException(playSource.getClass().getCanonicalName())); } private PlaySourceInternal getPlaySourceInternalFromFileSource(FileSource playSource) { FileSourceInternal fileSourceInternal = new FileSourceInternal().setUri(playSource.getUri()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.FILE) .setFileSource(fileSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromTextSource(TextSource playSource) { TextSourceInternal textSourceInternal = new TextSourceInternal().setText(playSource.getText()); if (playSource.getVoiceGender() != null) { textSourceInternal.setVoiceGender(GenderTypeInternal.fromString(playSource.getVoiceGender().toString())); } if (playSource.getSourceLocale() != null) { textSourceInternal.setSourceLocale(playSource.getSourceLocale()); } if (playSource.getVoiceName() != null) { textSourceInternal.setVoiceName(playSource.getVoiceName()); } PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.TEXT) .setTextSource(textSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal getPlaySourceInternalFromSsmlSource(SsmlSource playSource) { SsmlSourceInternal ssmlSourceInternal = new SsmlSourceInternal().setSsmlText(playSource.getSsmlText()); PlaySourceInternal playSourceInternal = new PlaySourceInternal() .setSourceType(PlaySourceTypeInternal.SSML) .setSsmlSource(ssmlSourceInternal) .setPlaySourceId(playSource.getPlaySourceId()); return playSourceInternal; } private PlaySourceInternal convertPlaySourceToPlaySourceInternal(PlaySource playSource) { PlaySourceInternal playSourceInternal = new PlaySourceInternal(); if (playSource instanceof FileSource) { playSourceInternal = getPlaySourceInternalFromFileSource((FileSource) playSource); } else if (playSource instanceof TextSource) { playSourceInternal = getPlaySourceInternalFromTextSource((TextSource) playSource); } return playSourceInternal; } private List<RecognizeChoiceInternal> convertListRecognizeChoiceInternal(List<RecognizeChoice> recognizeChoices) { return recognizeChoices.stream() .map(this::convertRecognizeChoiceInternal) .collect(Collectors.toList()); } private RecognizeChoiceInternal convertRecognizeChoiceInternal(RecognizeChoice recognizeChoice) { RecognizeChoiceInternal internalRecognizeChoice = new RecognizeChoiceInternal(); if (recognizeChoice.getLabel() != null) { internalRecognizeChoice.setLabel(recognizeChoice.getLabel()); } if (recognizeChoice.getPhrases() != null) { internalRecognizeChoice.setPhrases(recognizeChoice.getPhrases()); } if (recognizeChoice.getTone() != null) { internalRecognizeChoice.setTone(convertDtmfToneInternal(recognizeChoice.getTone())); } return internalRecognizeChoice; } private DtmfToneInternal convertDtmfToneInternal(DtmfTone dtmfTone) { return DtmfToneInternal.fromString(dtmfTone.toString()); } private RecognizeRequest getRecognizeRequestFromDtmfConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeDtmfOptions dtmfRecognizeOptions = (CallMediaRecognizeDtmfOptions) recognizeOptions; DtmfOptionsInternal dtmfOptionsInternal = if (dtmfRecognizeOptions.getStopTones() != null) { List<DtmfToneInternal> dtmfTones = dtmfRecognizeOptions.getStopTones().stream() .map(this::convertDtmfToneInternal) .collect(Collectors.toList()); dtmfOptionsInternal.setStopTones(dtmfTones); } RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setDtmfOptions(dtmfOptionsInternal) .setInterruptPrompt(recognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(recognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) recognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(recognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(recognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromChoiceConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeChoiceOptions choiceRecognizeOptions = (CallMediaRecognizeChoiceOptions) recognizeOptions; RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setChoices(convertListRecognizeChoiceInternal(choiceRecognizeOptions.getRecognizeChoices())) .setInterruptPrompt(choiceRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(choiceRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) choiceRecognizeOptions.getInitialSilenceTimeout().getSeconds()); if (choiceRecognizeOptions.getSpeechLanguage() != null) { if (!choiceRecognizeOptions.getSpeechLanguage().isEmpty()) { recognizeOptionsInternal.setSpeechLanguage(choiceRecognizeOptions.getSpeechLanguage()); } } PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(choiceRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(choiceRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private RecognizeRequest getRecognizeRequestFromSpeechConfiguration(CallMediaRecognizeOptions recognizeOptions) { CallMediaRecognizeSpeechOptions speechRecognizeOptions = (CallMediaRecognizeSpeechOptions) recognizeOptions; SpeechOptionsInternal speechOptionsInternal = new SpeechOptionsInternal().setEndSilenceTimeoutInMs(speechRecognizeOptions.getEndSilenceTimeoutInMs().toMillis()); RecognizeOptionsInternal recognizeOptionsInternal = new RecognizeOptionsInternal() .setSpeechOptions(speechOptionsInternal) .setInterruptPrompt(speechRecognizeOptions.isInterruptPrompt()) .setTargetParticipant(CommunicationIdentifierConverter.convert(speechRecognizeOptions.getTargetParticipant())); recognizeOptionsInternal.setInitialSilenceTimeoutInSeconds((int) speechRecognizeOptions.getInitialSilenceTimeout().getSeconds()); PlaySourceInternal playSourceInternal = getPlaySourceInternalFromRecognizeOptions(recognizeOptions); RecognizeRequest recognizeRequest = new RecognizeRequest() .setRecognizeInputType(RecognizeInputTypeInternal.fromString(speechRecognizeOptions.getRecognizeInputType().toString())) .setInterruptCallMediaOperation(speechRecognizeOptions.isInterruptCallMediaOperation()) .setPlayPrompt(playSourceInternal) .setRecognizeOptions(recognizeOptionsInternal) .setOperationContext(recognizeOptions.getOperationContext()); return recognizeRequest; } private PlaySourceInternal getPlaySourceInternalFromRecognizeOptions(CallMediaRecognizeOptions recognizeOptions) { PlaySourceInternal playSourceInternal = null; if (recognizeOptions.getPlayPrompt() != null) { PlaySource playSource = recognizeOptions.getPlayPrompt(); playSourceInternal = convertPlaySourceToPlaySourceInternal(playSource); } return playSourceInternal; } }
update to logger
public void stopRecording(Queue<String> variables) { HttpRequest request = new HttpRequest(HttpMethod.POST, String.format("%s/record/stop", proxyUrl.toString())) .setHeader(HttpHeaderName.CONTENT_TYPE, "application/json") .setHeader(X_RECORDING_ID, xRecordingId) .setBody(serializeVariables(variables)); client.sendSync(request, Context.NONE); }
client.sendSync(request, Context.NONE);
public void stopRecording(Queue<String> variables) { HttpRequest request = new HttpRequest(HttpMethod.POST, String.format("%s/record/stop", proxyUrl.toString())) .setHeader(HttpHeaderName.CONTENT_TYPE, "application/json") .setHeader(X_RECORDING_ID, xRecordingId) .setBody(serializeVariables(variables)); client.sendSync(request, Context.NONE); }
class TestProxyRecordPolicy implements HttpPipelinePolicy { private static final SerializerAdapter SERIALIZER = new JacksonAdapter(); private static final HttpHeaderName X_RECORDING_ID = HttpHeaderName.fromString("x-recording-id"); private final HttpClient client; private final URL proxyUrl; private String xRecordingId; private String assetJsonPath; private final List<TestProxySanitizer> sanitizers = new ArrayList<>(); private static final List<TestProxySanitizer> DEFAULT_SANITIZERS = loadSanitizers(); private static final ClientLogger LOGGER = new ClientLogger(TestProxyRecordPolicy.class); /** * Create an instance of {@link TestProxyRecordPolicy} with a list of custom sanitizers. * * @param httpClient The {@link HttpClient} to use. If none is passed {@link HttpURLConnectionHttpClient} is the default. * @param proxyUrl The {@link URL} for the test proxy instance. */ public TestProxyRecordPolicy(HttpClient httpClient, URL proxyUrl) { this.client = (httpClient == null ? new HttpURLConnectionHttpClient() : httpClient); this.proxyUrl = proxyUrl; this.sanitizers.addAll(DEFAULT_SANITIZERS); } /** * Starts a recording of test traffic. * * @param recordFile The name of the file to save the recording to. */ public void startRecording(String recordFile) { this.assetJsonPath = getAssetJsonPath(); HttpRequest request = new HttpRequest(HttpMethod.POST, String.format("%s/record/start", proxyUrl.toString())) .setBody(String.format("{\"x-recording-file\": \"%s\", \"x-recording-assets-file\": \"%s\"}", recordFile, assetJsonPath)); HttpResponse response = client.sendSync(request, Context.NONE); this.xRecordingId = response.getHeaderValue(X_RECORDING_ID); addProxySanitization(this.sanitizers); } private String getAssetJsonPath() { Path rootPath; try { rootPath = Paths.get(System.getProperty("user.dir") + "/.." + "/.." + "/..").toRealPath(); } catch (IOException e) { throw new RuntimeException(e); } return rootPath.relativize(Paths.get(System.getProperty("user.dir"))) + "assets.json"; } /** * Stops recording of test traffic. * @param variables A list of random variables generated during the test which is saved in the recording. */ /** * Transform the {@link Queue} containing variables into a JSON map for sending to the test proxy. * @param variables The variables to send. * @return A string containing the JSON map (or an empty map.) */ private String serializeVariables(Queue<String> variables) { if (variables.isEmpty()) { return "{}"; } int count = 0; Map<String, String> map = new LinkedHashMap<>(); for (String variable : variables) { map.put(String.valueOf(count++), variable); } try { return SERIALIZER.serialize(map, SerializerEncoding.JSON); } catch (IOException e) { throw new RuntimeException(e); } } @Override public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { TestProxyUtils.changeHeaders(context.getHttpRequest(), proxyUrl, xRecordingId, "record"); HttpResponse response = next.processSync(); TestProxyUtils.checkForTestProxyErrors(response); return TestProxyUtils.revertUrl(response); } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { HttpRequest request = context.getHttpRequest(); TestProxyUtils.changeHeaders(request, proxyUrl, xRecordingId, "record"); return next.process().map(response -> { TestProxyUtils.checkForTestProxyErrors(response); return TestProxyUtils.revertUrl(response); }); } /** * Add a list of {@link TestProxySanitizer} to the current recording session. * @param sanitizers The sanitizers to add. */ public void addProxySanitization(List<TestProxySanitizer> sanitizers) { if (isRecording()) { getSanitizerRequests(sanitizers, proxyUrl) .forEach(request -> { request.setHeader(X_RECORDING_ID, xRecordingId); client.sendSync(request, Context.NONE); }); } else { this.sanitizers.addAll(sanitizers); } } private boolean isRecording() { return xRecordingId != null; } }
class path * @throws RuntimeException Failed to serialize body payload. */ public void startRecording(File recordFile, Path testClassPath) { String assetJsonPath = getAssetJsonFile(recordFile, testClassPath); HttpRequest request = null; try { request = new HttpRequest(HttpMethod.POST, String.format("%s/record/start", proxyUrl.toString())) .setBody(SERIALIZER.serialize(new RecordFilePayload(recordFile.toString(), assetJsonPath), SerializerEncoding.JSON)) .setHeader(HttpHeaderName.CONTENT_TYPE, "application/json"); } catch (IOException e) { throw new RuntimeException(e); } HttpResponse response = client.sendSync(request, Context.NONE); this.xRecordingId = response.getHeaderValue(X_RECORDING_ID); addProxySanitization(this.sanitizers); setDefaultRecordingOptions(); }
may be log something?
private void validateReplicaAddresses(String collectionRid, AddressInformation[] addresses) { checkNotNull(addresses, "Argument 'addresses' can not be null"); checkArgument(StringUtils.isNotEmpty(collectionRid), "Argument 'collectionRid' can not be null"); List<Uri> addressesNeedToValidation = new ArrayList<>(); for (AddressInformation address : addresses) { if (this.replicaValidationScopes.contains(address.getPhysicalUri().getHealthStatus())) { switch (address.getPhysicalUri().getHealthStatus()) { case UnhealthyPending: addressesNeedToValidation.add(0, address.getPhysicalUri()); break; case Unknown: addressesNeedToValidation.add(address.getPhysicalUri()); break; default: break; } } } if (addressesNeedToValidation.size() > 0) { logger.debug("Addresses to validate: [{}]", addressesNeedToValidation); this.openConnectionsHandler .openConnections(collectionRid, this.serviceEndpoint, addressesNeedToValidation) .subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC) .subscribe(); } }
break;
private void validateReplicaAddresses(String collectionRid, AddressInformation[] addresses) { checkNotNull(addresses, "Argument 'addresses' can not be null"); checkArgument(StringUtils.isNotEmpty(collectionRid), "Argument 'collectionRid' can not be null"); List<Uri> addressesNeedToValidation = new ArrayList<>(); for (AddressInformation address : addresses) { if (this.replicaValidationScopes.contains(address.getPhysicalUri().getHealthStatus())) { switch (address.getPhysicalUri().getHealthStatus()) { case UnhealthyPending: addressesNeedToValidation.add(0, address.getPhysicalUri()); break; case Unknown: addressesNeedToValidation.add(address.getPhysicalUri()); break; default: logger.debug("Validate replica status is not support for status " + address.getPhysicalUri().getHealthStatus()); break; } } } if (addressesNeedToValidation.size() > 0) { logger.debug("Addresses to validate: [{}]", addressesNeedToValidation); this.openConnectionsHandler .openConnections(collectionRid, this.serviceEndpoint, addressesNeedToValidation) .subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC) .subscribe(); } }
class GatewayAddressCache implements IAddressCache { private static Duration minDurationBeforeEnforcingCollectionRoutingMapRefresh = Duration.ofSeconds(30); private final static Logger logger = LoggerFactory.getLogger(GatewayAddressCache.class); private final static String protocolFilterFormat = "%s eq %s"; private final static int DefaultBatchSize = 50; private final static int DefaultSuboptimalPartitionForceRefreshIntervalInSeconds = 600; private final DiagnosticsClientContext clientContext; private final String databaseFeedEntryUrl = PathsHelper.generatePath(ResourceType.Database, "", true); private final URI addressEndpoint; private final URI serviceEndpoint; private final AsyncCacheNonBlocking<PartitionKeyRangeIdentity, AddressInformation[]> serverPartitionAddressCache; private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> suboptimalServerPartitionTimestamps; private final long suboptimalPartitionForceRefreshIntervalInSeconds; private final String protocolScheme; private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap<String, String> defaultRequestHeaders; private final HttpClient httpClient; private volatile Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; private final ConcurrentHashMap<String, ForcedRefreshMetadata> lastForcedRefreshMap; private final GlobalEndpointManager globalEndpointManager; private IOpenConnectionsHandler openConnectionsHandler; private final ConnectionPolicy connectionPolicy; private final boolean replicaAddressValidationEnabled; private final Set<Uri.HealthStatus> replicaValidationScopes; public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this.clientContext = clientContext; try { this.addressEndpoint = new URL(serviceEndpoint.toURL(), Paths.ADDRESS_PATH_SEGMENT).toURI(); } catch (MalformedURLException | URISyntaxException e) { logger.error("serviceEndpoint {} is invalid", serviceEndpoint, e); assert false; throw new IllegalStateException(e); } this.serviceEndpoint = serviceEndpoint; this.tokenProvider = tokenProvider; this.serverPartitionAddressCache = new AsyncCacheNonBlocking<>(); this.suboptimalServerPartitionTimestamps = new ConcurrentHashMap<>(); this.suboptimalMasterPartitionTimestamp = Instant.MAX; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.protocolScheme = protocol.scheme(); this.protocolFilter = String.format(GatewayAddressCache.protocolFilterFormat, Constants.Properties.PROTOCOL, this.protocolScheme); this.httpClient = httpClient; if (userAgent == null) { userAgent = new UserAgentContainer(); } defaultRequestHeaders = new HashMap<>(); defaultRequestHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); if(apiType != null) { defaultRequestHeaders.put(HttpConstants.HttpHeaders.API_TYPE, apiType.toString()); } defaultRequestHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.defaultRequestHeaders.put( HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); this.lastForcedRefreshMap = new ConcurrentHashMap<>(); this.globalEndpointManager = globalEndpointManager; this.openConnectionsHandler = openConnectionsHandler; this.connectionPolicy = connectionPolicy; this.replicaAddressValidationEnabled = Configs.isReplicaAddressValidationEnabled(); this.replicaValidationScopes = ConcurrentHashMap.newKeySet(); if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.UnhealthyPending); } } public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this(clientContext, serviceEndpoint, protocol, tokenProvider, userAgent, httpClient, DefaultSuboptimalPartitionForceRefreshIntervalInSeconds, apiType, globalEndpointManager, connectionPolicy, openConnectionsHandler); } @Override public Mono<Utils.ValueHolder<AddressInformation[]>> tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); logger.debug("PartitionKeyRangeIdentity {}, forceRefreshPartitionAddresses {}", partitionKeyRangeIdentity, forceRefreshPartitionAddresses); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties) .map(partitionKeyRangeIdentityPair -> new Utils.ValueHolder<>(partitionKeyRangeIdentityPair.getRight())); } evaluateCollectionRoutingMapRefreshForServerPartition( request, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); if (suboptimalServerPartitionTimestamp != null) { logger.debug("suboptimalServerPartitionTimestamp is {}", suboptimalServerPartitionTimestamp); boolean forceRefreshDueToSuboptimalPartitionReplicaSet = Duration.between(suboptimalServerPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds; if (forceRefreshDueToSuboptimalPartitionReplicaSet) { Instant newValue = this.suboptimalServerPartitionTimestamps.computeIfPresent(partitionKeyRangeIdentity, (key, oldVal) -> { logger.debug("key = {}, oldValue = {}", key, oldVal); if (suboptimalServerPartitionTimestamp.equals(oldVal)) { return Instant.MAX; } else { return oldVal; } }); logger.debug("newValue is {}", newValue); if (!suboptimalServerPartitionTimestamp.equals(newValue)) { logger.debug("setting forceRefreshPartitionAddresses to true"); forceRefreshPartitionAddresses = true; } } } final boolean forceRefreshPartitionAddressesModified = forceRefreshPartitionAddresses; if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } Mono<Utils.ValueHolder<AddressInformation[]>> addressesObs = this.serverPartitionAddressCache .getAsync( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId( request, partitionKeyRangeIdentity, forceRefreshPartitionAddressesModified, cachedAddresses), cachedAddresses -> { for (Uri failedEndpoints : request.requestContext.getFailedEndpoints()) { failedEndpoints.setUnhealthy(); } return forceRefreshPartitionAddressesModified; }) .map(Utils.ValueHolder::new); return addressesObs .map(addressesValueHolder -> { if (notAllReplicasAvailable(addressesValueHolder.v)) { if (logger.isDebugEnabled()) { logger.debug("not all replicas available {}", JavaStreamUtils.info(addressesValueHolder.v)); } this.suboptimalServerPartitionTimestamps.putIfAbsent(partitionKeyRangeIdentity, Instant.now()); } if (Arrays .stream(addressesValueHolder.v) .anyMatch(addressInformation -> addressInformation.getPhysicalUri().shouldRefreshHealthStatus())) { logger.debug("refresh cache due to address uri in unhealthy status for pkRangeId {}", partitionKeyRangeIdentity.getPartitionKeyRangeId()); this.serverPartitionAddressCache.refresh( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId(request, partitionKeyRangeIdentity, true, cachedAddresses)); } return addressesValueHolder; }) .onErrorResume(ex -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(ex); CosmosException dce = Utils.as(unwrappedException, CosmosException.class); if (dce == null) { logger.error("unexpected failure", ex); if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } return Mono.error(unwrappedException); } else { logger.debug("tryGetAddresses dce", dce); if (Exceptions.isNotFound(dce) || Exceptions.isGone(dce) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); logger.debug("tryGetAddresses: inner onErrorResumeNext return null", dce); return Mono.just(new Utils.ValueHolder<>(null)); } return Mono.error(unwrappedException); } }); } @Override public void setOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler) { this.openConnectionsHandler = openConnectionsHandler; } public Mono<List<Address>> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid, JavaStreamUtils.toString(partitionKeyRangeIds, ",")); } request.setAddressRefresh(true, forceRefresh); String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true); HashMap<String, String> addressQuery = new HashMap<>(); addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = null; try { token = this.tokenProvider.getUserAuthorizationToken( collectionRid, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } catch (UnauthorizedException e) { if (logger.isDebugEnabled()) { logger.debug("User doesn't have resource token for collection rid {}", collectionRid); } } if (token == null && request.getIsNameBased()) { String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress()); token = this.tokenProvider.getUserAuthorizationToken( collectionAltLink, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } token = HttpUtils.urlEncode(token); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart( request, targetEndpoint, forceRefresh, request.forceCollectionRoutingMapRefresh); headers.put(HttpConstants.HttpHeaders.ACTIVITY_ID, identifier); HttpHeaders httpHeaders = new HttpHeaders(headers); Instant addressCallStartTime = Instant.now(); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(httpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.SERVER_ADDRESS_LOOKUP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync deserializes result"); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } public void dispose() { } private Mono<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map<String, Object> properties) { logger.debug("resolveMasterAsync forceRefresh: {}", forceRefresh); Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || (masterAddressAndRangeInitial != null && notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { Mono<List<Address>> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, databaseFeedEntryUrl, forceRefresh, false, properties); return masterReplicaAddressesObs.map( masterAddresses -> { Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeRes = this.toPartitionAddressAndRange("", masterAddresses); this.masterPartitionAddressCache = masterAddressAndRangeRes; if (notAllReplicasAvailable(masterAddressAndRangeRes.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } else { this.suboptimalMasterPartitionTimestamp = Instant.MAX; } return masterPartitionAddressCache; }) .doOnError( e -> { this.suboptimalMasterPartitionTimestamp = Instant.MAX; }); } else { if (notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } return Mono.just(masterAddressAndRangeInitial); } } private void evaluateCollectionRoutingMapRefreshForServerPartition( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); if (forceRefreshPartitionAddresses) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); if (request.forceCollectionRoutingMapRefresh) { forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else if (forcedRefreshMetadata.shouldIncludeCollectionRoutingMapRefresh(pkRangeIdentity)) { request.forceCollectionRoutingMapRefresh = true; forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else { forcedRefreshMetadata.signalPartitionAddressOnlyRefresh(pkRangeIdentity); } } else if (request.forceCollectionRoutingMapRefresh) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, false); } logger.debug("evaluateCollectionRoutingMapRefreshForServerPartition collectionRid {}, partitionKeyRangeId {}," + " " + "forceRefreshPartitionAddresses {}, forceCollectionRoutingMapRefresh {}", collectionRid, partitionKeyRangeId, forceRefreshPartitionAddresses, request.forceCollectionRoutingMapRefresh); } private void validatePkRangeIdentity(PartitionKeyRangeIdentity pkRangeIdentity) { Utils.checkNotNullOrThrow(pkRangeIdentity, "pkRangeId", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getCollectionRid(), "pkRangeId.getCollectionRid()", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getPartitionKeyRangeId(), "pkRangeId.getPartitionKeyRangeId()", ""); } private Mono<AddressInformation[]> getAddressesForRangeId( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefresh, AddressInformation[] cachedAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); logger.debug( "getAddressesForRangeId collectionRid {}, partitionKeyRangeId {}, forceRefresh {}", collectionRid, partitionKeyRangeId, forceRefresh); Mono<List<Address>> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> addressInfos = addressResponse.map( addresses -> { if (logger.isDebugEnabled()) { logger.debug("addresses from getServerAddressesViaGatewayAsync in getAddressesForRangeId {}", JavaStreamUtils.info(addresses)); } return addresses .stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList()); }); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> result = addressInfos .map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); return result .flatMap( list -> { if (logger.isDebugEnabled()) { logger.debug("getAddressesForRangeId flatMap got result {}", JavaStreamUtils.info(list)); } if (list.isEmpty()) { String errorMessage = String.format( RMResources.PartitionKeyRangeNotFound, partitionKeyRangeId, collectionRid); PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); return Mono.error(e); } else { AddressInformation[] mergedAddresses = this.mergeAddresses(list.get(0).getRight(), cachedAddresses); for (AddressInformation address : mergedAddresses) { address.getPhysicalUri().setRefreshed(); } if (this.replicaAddressValidationEnabled) { this.validateReplicaAddresses(collectionRid, mergedAddresses); } return Mono.just(mergedAddresses); } }) .doOnError(e -> logger.debug("getAddressesForRangeId", e)); } public Mono<List<Address>> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, String entryUrl, boolean forceRefresh, boolean useMasterCollectionResolver, Map<String, Object> properties) { logger.debug("getMasterAddressesViaGatewayAsync " + "resourceType {}, " + "resourceAddress {}, " + "entryUrl {}, " + "forceRefresh {}, " + "useMasterCollectionResolver {}", resourceType, resourceAddress, entryUrl, forceRefresh, useMasterCollectionResolver ); request.setAddressRefresh(true, forceRefresh); HashMap<String, String> queryParameters = new HashMap<>(); queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (useMasterCollectionResolver) { headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, "true"); } if(request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = this.tokenProvider.getUserAuthorizationToken( resourceAddress, resourceType, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, properties); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart( request, targetEndpoint, true, true); headers.put(HttpConstants.HttpHeaders.ACTIVITY_ID, identifier); HttpHeaders defaultHttpHeaders = new HttpHeaders(headers); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), defaultHttpHeaders); Instant addressCallStartTime = Instant.now(); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(defaultHttpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, this.clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.MASTER_ADDRESS_LOOK_UP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } /*** * merge the new addresses get back from gateway with the cached addresses. * If the address is being returned from gateway again, then keep using the cached addressInformation object * If it is a new address being returned, then use the new addressInformation object. * * @param newAddresses the latest addresses being returned from gateway. * @param cachedAddresses the cached addresses. * * @return the merged addresses. */ private AddressInformation[] mergeAddresses(AddressInformation[] newAddresses, AddressInformation[] cachedAddresses) { checkNotNull(newAddresses, "Argument 'newAddresses' should not be null"); if (cachedAddresses == null) { return newAddresses; } List<AddressInformation> mergedAddresses = new ArrayList<>(); Map<Uri, List<AddressInformation>> cachedAddressMap = Arrays .stream(cachedAddresses) .collect(Collectors.groupingBy(AddressInformation::getPhysicalUri)); for (AddressInformation newAddress : newAddresses) { boolean useCachedAddress = false; if (cachedAddressMap.containsKey(newAddress.getPhysicalUri())) { for (AddressInformation cachedAddress : cachedAddressMap.get(newAddress.getPhysicalUri())) { if (newAddress.getProtocol() == cachedAddress.getProtocol() && newAddress.isPublic() == cachedAddress.isPublic() && newAddress.isPrimary() == cachedAddress.isPrimary()) { useCachedAddress = true; mergedAddresses.add(cachedAddress); break; } } } if (!useCachedAddress) { mergedAddresses.add(newAddress); } } return mergedAddresses.toArray(new AddressInformation[mergedAddresses.size()]); } private Pair<PartitionKeyRangeIdentity, AddressInformation[]> toPartitionAddressAndRange(String collectionRid, List<Address> addresses) { if (logger.isDebugEnabled()) { logger.debug("toPartitionAddressAndRange"); } Address address = addresses.get(0); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, address.getParitionKeyRangeId()); AddressInformation[] addressInfos = addresses .stream() .map(addr -> GatewayAddressCache.toAddressInformation(addr)) .collect(Collectors.toList()) .toArray(new AddressInformation[addresses.size()]); return Pair.of(partitionKeyRangeIdentity, addressInfos); } private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.isPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } public Flux<OpenConnectionResponse> openConnectionsAndInitCaches( DocumentCollection collection, List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) { checkNotNull(collection, "Argument 'collection' should not be null"); checkNotNull(partitionKeyRangeIdentities, "Argument 'partitionKeyRangeIdentities' should not be null"); if (logger.isDebugEnabled()) { logger.debug( "openConnectionsAndInitCaches collection: {}, partitionKeyRangeIdentities: {}", collection.getResourceId(), JavaStreamUtils.toString(partitionKeyRangeIdentities, ",")); } if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.Unknown); } List<Flux<List<Address>>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this.clientContext, OperationType.Read, collection.getResourceId(), ResourceType.DocumentCollection, Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; endIndex = Math.min(endIndex, partitionKeyRangeIdentities.size()); tasks.add( this.getServerAddressesViaGatewayWithRetry( request, collection.getResourceId(), partitionKeyRangeIdentities .subList(i, endIndex) .stream() .map(PartitionKeyRangeIdentity::getPartitionKeyRangeId) .collect(Collectors.toList()), false).flux()); } return Flux.concat(tasks) .flatMap(list -> { List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream().map(addresses -> toPartitionAddressAndRange(collection.getResourceId(), addresses)) .collect(Collectors.toList()); return Flux.fromIterable(addressInfos) .flatMap( addressInfo -> { this.serverPartitionAddressCache.set(addressInfo.getLeft(), addressInfo.getRight()); if (this.openConnectionsHandler != null) { return this.openConnectionsHandler.openConnections( collection.getResourceId(), this.serviceEndpoint, Arrays .stream(addressInfo.getRight()) .map(addressInformation -> addressInformation.getPhysicalUri()) .collect(Collectors.toList())); } logger.info("OpenConnectionHandler is null, can not open connections"); return Flux.empty(); }, Configs.getCPUCnt() * 10, Configs.getCPUCnt() * 3); }); } private Mono<List<Address>> getServerAddressesViaGatewayWithRetry( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { OpenConnectionAndInitCachesRetryPolicy openConnectionAndInitCachesRetryPolicy = new OpenConnectionAndInitCachesRetryPolicy(this.connectionPolicy.getThrottlingRetryOptions()); return BackoffRetryUtility.executeRetry( () -> this.getServerAddressesViaGatewayAsync(request, collectionRid, partitionKeyRangeIds, forceRefresh), openConnectionAndInitCachesRetryPolicy); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart( RxDocumentServiceRequest request, URI targetEndpointUrl, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { if (request.requestContext.cosmosDiagnostics != null) { return BridgeInternal.recordAddressResolutionStart( request.requestContext.cosmosDiagnostics, targetEndpointUrl, forceRefresh, forceCollectionRoutingMapRefresh); } return null; } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier, String errorMessage) { if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosDiagnostics, identifier, errorMessage); } } private static class ForcedRefreshMetadata { private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> lastPartitionAddressOnlyRefresh; private Instant lastCollectionRoutingMapRefresh; public ForcedRefreshMetadata() { lastPartitionAddressOnlyRefresh = new ConcurrentHashMap<>(); lastCollectionRoutingMapRefresh = Instant.now(); } public void signalCollectionRoutingMapRefresh( PartitionKeyRangeIdentity pk, boolean forcePartitionAddressRefresh) { Instant nowSnapshot = Instant.now(); if (forcePartitionAddressRefresh) { lastPartitionAddressOnlyRefresh.put(pk, nowSnapshot); } lastCollectionRoutingMapRefresh = nowSnapshot; } public void signalPartitionAddressOnlyRefresh(PartitionKeyRangeIdentity pk) { lastPartitionAddressOnlyRefresh.put(pk, Instant.now()); } public boolean shouldIncludeCollectionRoutingMapRefresh(PartitionKeyRangeIdentity pk) { Instant lastPartitionAddressRefreshSnapshot = lastPartitionAddressOnlyRefresh.get(pk); Instant lastCollectionRoutingMapRefreshSnapshot = lastCollectionRoutingMapRefresh; if (lastPartitionAddressRefreshSnapshot == null || !lastPartitionAddressRefreshSnapshot.isAfter(lastCollectionRoutingMapRefreshSnapshot)) { return false; } Duration durationSinceLastForcedCollectionRoutingMapRefresh = Duration.between(lastCollectionRoutingMapRefreshSnapshot, Instant.now()); boolean returnValue = durationSinceLastForcedCollectionRoutingMapRefresh .compareTo(minDurationBeforeEnforcingCollectionRoutingMapRefresh) >= 0; return returnValue; } } }
class GatewayAddressCache implements IAddressCache { private static Duration minDurationBeforeEnforcingCollectionRoutingMapRefresh = Duration.ofSeconds(30); private final static Logger logger = LoggerFactory.getLogger(GatewayAddressCache.class); private final static String protocolFilterFormat = "%s eq %s"; private final static int DefaultBatchSize = 50; private final static int DefaultSuboptimalPartitionForceRefreshIntervalInSeconds = 600; private final DiagnosticsClientContext clientContext; private final String databaseFeedEntryUrl = PathsHelper.generatePath(ResourceType.Database, "", true); private final URI addressEndpoint; private final URI serviceEndpoint; private final AsyncCacheNonBlocking<PartitionKeyRangeIdentity, AddressInformation[]> serverPartitionAddressCache; private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> suboptimalServerPartitionTimestamps; private final long suboptimalPartitionForceRefreshIntervalInSeconds; private final String protocolScheme; private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap<String, String> defaultRequestHeaders; private final HttpClient httpClient; private volatile Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; private final ConcurrentHashMap<String, ForcedRefreshMetadata> lastForcedRefreshMap; private final GlobalEndpointManager globalEndpointManager; private IOpenConnectionsHandler openConnectionsHandler; private final ConnectionPolicy connectionPolicy; private final boolean replicaAddressValidationEnabled; private final Set<Uri.HealthStatus> replicaValidationScopes; public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this.clientContext = clientContext; try { this.addressEndpoint = new URL(serviceEndpoint.toURL(), Paths.ADDRESS_PATH_SEGMENT).toURI(); } catch (MalformedURLException | URISyntaxException e) { logger.error("serviceEndpoint {} is invalid", serviceEndpoint, e); assert false; throw new IllegalStateException(e); } this.serviceEndpoint = serviceEndpoint; this.tokenProvider = tokenProvider; this.serverPartitionAddressCache = new AsyncCacheNonBlocking<>(); this.suboptimalServerPartitionTimestamps = new ConcurrentHashMap<>(); this.suboptimalMasterPartitionTimestamp = Instant.MAX; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.protocolScheme = protocol.scheme(); this.protocolFilter = String.format(GatewayAddressCache.protocolFilterFormat, Constants.Properties.PROTOCOL, this.protocolScheme); this.httpClient = httpClient; if (userAgent == null) { userAgent = new UserAgentContainer(); } defaultRequestHeaders = new HashMap<>(); defaultRequestHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); if(apiType != null) { defaultRequestHeaders.put(HttpConstants.HttpHeaders.API_TYPE, apiType.toString()); } defaultRequestHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.defaultRequestHeaders.put( HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); this.lastForcedRefreshMap = new ConcurrentHashMap<>(); this.globalEndpointManager = globalEndpointManager; this.openConnectionsHandler = openConnectionsHandler; this.connectionPolicy = connectionPolicy; this.replicaAddressValidationEnabled = Configs.isReplicaAddressValidationEnabled(); this.replicaValidationScopes = ConcurrentHashMap.newKeySet(); if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.UnhealthyPending); } } public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this(clientContext, serviceEndpoint, protocol, tokenProvider, userAgent, httpClient, DefaultSuboptimalPartitionForceRefreshIntervalInSeconds, apiType, globalEndpointManager, connectionPolicy, openConnectionsHandler); } @Override public Mono<Utils.ValueHolder<AddressInformation[]>> tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); logger.debug("PartitionKeyRangeIdentity {}, forceRefreshPartitionAddresses {}", partitionKeyRangeIdentity, forceRefreshPartitionAddresses); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties) .map(partitionKeyRangeIdentityPair -> new Utils.ValueHolder<>(partitionKeyRangeIdentityPair.getRight())); } evaluateCollectionRoutingMapRefreshForServerPartition( request, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); if (suboptimalServerPartitionTimestamp != null) { logger.debug("suboptimalServerPartitionTimestamp is {}", suboptimalServerPartitionTimestamp); boolean forceRefreshDueToSuboptimalPartitionReplicaSet = Duration.between(suboptimalServerPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds; if (forceRefreshDueToSuboptimalPartitionReplicaSet) { Instant newValue = this.suboptimalServerPartitionTimestamps.computeIfPresent(partitionKeyRangeIdentity, (key, oldVal) -> { logger.debug("key = {}, oldValue = {}", key, oldVal); if (suboptimalServerPartitionTimestamp.equals(oldVal)) { return Instant.MAX; } else { return oldVal; } }); logger.debug("newValue is {}", newValue); if (!suboptimalServerPartitionTimestamp.equals(newValue)) { logger.debug("setting forceRefreshPartitionAddresses to true"); forceRefreshPartitionAddresses = true; } } } final boolean forceRefreshPartitionAddressesModified = forceRefreshPartitionAddresses; if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } Mono<Utils.ValueHolder<AddressInformation[]>> addressesObs = this.serverPartitionAddressCache .getAsync( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId( request, partitionKeyRangeIdentity, forceRefreshPartitionAddressesModified, cachedAddresses), cachedAddresses -> { for (Uri failedEndpoints : request.requestContext.getFailedEndpoints()) { failedEndpoints.setUnhealthy(); } return forceRefreshPartitionAddressesModified; }) .map(Utils.ValueHolder::new); return addressesObs .map(addressesValueHolder -> { if (notAllReplicasAvailable(addressesValueHolder.v)) { if (logger.isDebugEnabled()) { logger.debug("not all replicas available {}", JavaStreamUtils.info(addressesValueHolder.v)); } this.suboptimalServerPartitionTimestamps.putIfAbsent(partitionKeyRangeIdentity, Instant.now()); } if (Arrays .stream(addressesValueHolder.v) .anyMatch(addressInformation -> addressInformation.getPhysicalUri().shouldRefreshHealthStatus())) { logger.debug("refresh cache due to address uri in unhealthy status for pkRangeId {}", partitionKeyRangeIdentity.getPartitionKeyRangeId()); this.serverPartitionAddressCache.refresh( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId(request, partitionKeyRangeIdentity, true, cachedAddresses)); } return addressesValueHolder; }) .onErrorResume(ex -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(ex); CosmosException dce = Utils.as(unwrappedException, CosmosException.class); if (dce == null) { logger.error("unexpected failure", ex); if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } return Mono.error(unwrappedException); } else { logger.debug("tryGetAddresses dce", dce); if (Exceptions.isNotFound(dce) || Exceptions.isGone(dce) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); logger.debug("tryGetAddresses: inner onErrorResumeNext return null", dce); return Mono.just(new Utils.ValueHolder<>(null)); } return Mono.error(unwrappedException); } }); } @Override public void setOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler) { this.openConnectionsHandler = openConnectionsHandler; } public Mono<List<Address>> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid, JavaStreamUtils.toString(partitionKeyRangeIds, ",")); } request.setAddressRefresh(true, forceRefresh); String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true); HashMap<String, String> addressQuery = new HashMap<>(); addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = null; try { token = this.tokenProvider.getUserAuthorizationToken( collectionRid, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } catch (UnauthorizedException e) { if (logger.isDebugEnabled()) { logger.debug("User doesn't have resource token for collection rid {}", collectionRid); } } if (token == null && request.getIsNameBased()) { String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress()); token = this.tokenProvider.getUserAuthorizationToken( collectionAltLink, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } token = HttpUtils.urlEncode(token); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart( request, targetEndpoint, forceRefresh, request.forceCollectionRoutingMapRefresh); headers.put(HttpConstants.HttpHeaders.ACTIVITY_ID, identifier); HttpHeaders httpHeaders = new HttpHeaders(headers); Instant addressCallStartTime = Instant.now(); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(httpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.SERVER_ADDRESS_LOOKUP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync deserializes result"); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } public void dispose() { } private Mono<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map<String, Object> properties) { logger.debug("resolveMasterAsync forceRefresh: {}", forceRefresh); Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || (masterAddressAndRangeInitial != null && notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { Mono<List<Address>> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, databaseFeedEntryUrl, forceRefresh, false, properties); return masterReplicaAddressesObs.map( masterAddresses -> { Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeRes = this.toPartitionAddressAndRange("", masterAddresses); this.masterPartitionAddressCache = masterAddressAndRangeRes; if (notAllReplicasAvailable(masterAddressAndRangeRes.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } else { this.suboptimalMasterPartitionTimestamp = Instant.MAX; } return masterPartitionAddressCache; }) .doOnError( e -> { this.suboptimalMasterPartitionTimestamp = Instant.MAX; }); } else { if (notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } return Mono.just(masterAddressAndRangeInitial); } } private void evaluateCollectionRoutingMapRefreshForServerPartition( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); if (forceRefreshPartitionAddresses) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); if (request.forceCollectionRoutingMapRefresh) { forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else if (forcedRefreshMetadata.shouldIncludeCollectionRoutingMapRefresh(pkRangeIdentity)) { request.forceCollectionRoutingMapRefresh = true; forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else { forcedRefreshMetadata.signalPartitionAddressOnlyRefresh(pkRangeIdentity); } } else if (request.forceCollectionRoutingMapRefresh) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, false); } logger.debug("evaluateCollectionRoutingMapRefreshForServerPartition collectionRid {}, partitionKeyRangeId {}," + " " + "forceRefreshPartitionAddresses {}, forceCollectionRoutingMapRefresh {}", collectionRid, partitionKeyRangeId, forceRefreshPartitionAddresses, request.forceCollectionRoutingMapRefresh); } private void validatePkRangeIdentity(PartitionKeyRangeIdentity pkRangeIdentity) { Utils.checkNotNullOrThrow(pkRangeIdentity, "pkRangeId", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getCollectionRid(), "pkRangeId.getCollectionRid()", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getPartitionKeyRangeId(), "pkRangeId.getPartitionKeyRangeId()", ""); } private Mono<AddressInformation[]> getAddressesForRangeId( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefresh, AddressInformation[] cachedAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); logger.debug( "getAddressesForRangeId collectionRid {}, partitionKeyRangeId {}, forceRefresh {}", collectionRid, partitionKeyRangeId, forceRefresh); Mono<List<Address>> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> addressInfos = addressResponse.map( addresses -> { if (logger.isDebugEnabled()) { logger.debug("addresses from getServerAddressesViaGatewayAsync in getAddressesForRangeId {}", JavaStreamUtils.info(addresses)); } return addresses .stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList()); }); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> result = addressInfos .map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); return result .flatMap( list -> { if (logger.isDebugEnabled()) { logger.debug("getAddressesForRangeId flatMap got result {}", JavaStreamUtils.info(list)); } if (list.isEmpty()) { String errorMessage = String.format( RMResources.PartitionKeyRangeNotFound, partitionKeyRangeId, collectionRid); PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); return Mono.error(e); } else { AddressInformation[] mergedAddresses = this.mergeAddresses(list.get(0).getRight(), cachedAddresses); for (AddressInformation address : mergedAddresses) { address.getPhysicalUri().setRefreshed(); } if (this.replicaAddressValidationEnabled) { this.validateReplicaAddresses(collectionRid, mergedAddresses); } return Mono.just(mergedAddresses); } }) .doOnError(e -> logger.debug("getAddressesForRangeId", e)); } public Mono<List<Address>> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, String entryUrl, boolean forceRefresh, boolean useMasterCollectionResolver, Map<String, Object> properties) { logger.debug("getMasterAddressesViaGatewayAsync " + "resourceType {}, " + "resourceAddress {}, " + "entryUrl {}, " + "forceRefresh {}, " + "useMasterCollectionResolver {}", resourceType, resourceAddress, entryUrl, forceRefresh, useMasterCollectionResolver ); request.setAddressRefresh(true, forceRefresh); HashMap<String, String> queryParameters = new HashMap<>(); queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (useMasterCollectionResolver) { headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, "true"); } if(request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = this.tokenProvider.getUserAuthorizationToken( resourceAddress, resourceType, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, properties); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart( request, targetEndpoint, true, true); headers.put(HttpConstants.HttpHeaders.ACTIVITY_ID, identifier); HttpHeaders defaultHttpHeaders = new HttpHeaders(headers); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), defaultHttpHeaders); Instant addressCallStartTime = Instant.now(); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(defaultHttpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, this.clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.MASTER_ADDRESS_LOOK_UP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } /*** * merge the new addresses get back from gateway with the cached addresses. * If the address is being returned from gateway again, then keep using the cached addressInformation object * If it is a new address being returned, then use the new addressInformation object. * * @param newAddresses the latest addresses being returned from gateway. * @param cachedAddresses the cached addresses. * * @return the merged addresses. */ private AddressInformation[] mergeAddresses(AddressInformation[] newAddresses, AddressInformation[] cachedAddresses) { checkNotNull(newAddresses, "Argument 'newAddresses' should not be null"); if (cachedAddresses == null) { return newAddresses; } List<AddressInformation> mergedAddresses = new ArrayList<>(); Map<Uri, List<AddressInformation>> cachedAddressMap = Arrays .stream(cachedAddresses) .collect(Collectors.groupingBy(AddressInformation::getPhysicalUri)); for (AddressInformation newAddress : newAddresses) { boolean useCachedAddress = false; if (cachedAddressMap.containsKey(newAddress.getPhysicalUri())) { for (AddressInformation cachedAddress : cachedAddressMap.get(newAddress.getPhysicalUri())) { if (newAddress.getProtocol() == cachedAddress.getProtocol() && newAddress.isPublic() == cachedAddress.isPublic() && newAddress.isPrimary() == cachedAddress.isPrimary()) { useCachedAddress = true; mergedAddresses.add(cachedAddress); break; } } } if (!useCachedAddress) { mergedAddresses.add(newAddress); } } return mergedAddresses.toArray(new AddressInformation[mergedAddresses.size()]); } private Pair<PartitionKeyRangeIdentity, AddressInformation[]> toPartitionAddressAndRange(String collectionRid, List<Address> addresses) { if (logger.isDebugEnabled()) { logger.debug("toPartitionAddressAndRange"); } Address address = addresses.get(0); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, address.getParitionKeyRangeId()); AddressInformation[] addressInfos = addresses .stream() .map(addr -> GatewayAddressCache.toAddressInformation(addr)) .collect(Collectors.toList()) .toArray(new AddressInformation[addresses.size()]); return Pair.of(partitionKeyRangeIdentity, addressInfos); } private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.isPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } public Flux<OpenConnectionResponse> openConnectionsAndInitCaches( DocumentCollection collection, List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) { checkNotNull(collection, "Argument 'collection' should not be null"); checkNotNull(partitionKeyRangeIdentities, "Argument 'partitionKeyRangeIdentities' should not be null"); if (logger.isDebugEnabled()) { logger.debug( "openConnectionsAndInitCaches collection: {}, partitionKeyRangeIdentities: {}", collection.getResourceId(), JavaStreamUtils.toString(partitionKeyRangeIdentities, ",")); } if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.Unknown); } List<Flux<List<Address>>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this.clientContext, OperationType.Read, collection.getResourceId(), ResourceType.DocumentCollection, Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; endIndex = Math.min(endIndex, partitionKeyRangeIdentities.size()); tasks.add( this.getServerAddressesViaGatewayWithRetry( request, collection.getResourceId(), partitionKeyRangeIdentities .subList(i, endIndex) .stream() .map(PartitionKeyRangeIdentity::getPartitionKeyRangeId) .collect(Collectors.toList()), false).flux()); } return Flux.concat(tasks) .flatMap(list -> { List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream().map(addresses -> toPartitionAddressAndRange(collection.getResourceId(), addresses)) .collect(Collectors.toList()); return Flux.fromIterable(addressInfos) .flatMap( addressInfo -> { this.serverPartitionAddressCache.set(addressInfo.getLeft(), addressInfo.getRight()); if (this.openConnectionsHandler != null) { return this.openConnectionsHandler.openConnections( collection.getResourceId(), this.serviceEndpoint, Arrays .stream(addressInfo.getRight()) .map(addressInformation -> addressInformation.getPhysicalUri()) .collect(Collectors.toList())); } logger.info("OpenConnectionHandler is null, can not open connections"); return Flux.empty(); }, Configs.getCPUCnt() * 10, Configs.getCPUCnt() * 3); }); } private Mono<List<Address>> getServerAddressesViaGatewayWithRetry( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { OpenConnectionAndInitCachesRetryPolicy openConnectionAndInitCachesRetryPolicy = new OpenConnectionAndInitCachesRetryPolicy(this.connectionPolicy.getThrottlingRetryOptions()); return BackoffRetryUtility.executeRetry( () -> this.getServerAddressesViaGatewayAsync(request, collectionRid, partitionKeyRangeIds, forceRefresh), openConnectionAndInitCachesRetryPolicy); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart( RxDocumentServiceRequest request, URI targetEndpointUrl, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { if (request.requestContext.cosmosDiagnostics != null) { return BridgeInternal.recordAddressResolutionStart( request.requestContext.cosmosDiagnostics, targetEndpointUrl, forceRefresh, forceCollectionRoutingMapRefresh); } return null; } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier, String errorMessage) { if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosDiagnostics, identifier, errorMessage); } } private static class ForcedRefreshMetadata { private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> lastPartitionAddressOnlyRefresh; private Instant lastCollectionRoutingMapRefresh; public ForcedRefreshMetadata() { lastPartitionAddressOnlyRefresh = new ConcurrentHashMap<>(); lastCollectionRoutingMapRefresh = Instant.now(); } public void signalCollectionRoutingMapRefresh( PartitionKeyRangeIdentity pk, boolean forcePartitionAddressRefresh) { Instant nowSnapshot = Instant.now(); if (forcePartitionAddressRefresh) { lastPartitionAddressOnlyRefresh.put(pk, nowSnapshot); } lastCollectionRoutingMapRefresh = nowSnapshot; } public void signalPartitionAddressOnlyRefresh(PartitionKeyRangeIdentity pk) { lastPartitionAddressOnlyRefresh.put(pk, Instant.now()); } public boolean shouldIncludeCollectionRoutingMapRefresh(PartitionKeyRangeIdentity pk) { Instant lastPartitionAddressRefreshSnapshot = lastPartitionAddressOnlyRefresh.get(pk); Instant lastCollectionRoutingMapRefreshSnapshot = lastCollectionRoutingMapRefresh; if (lastPartitionAddressRefreshSnapshot == null || !lastPartitionAddressRefreshSnapshot.isAfter(lastCollectionRoutingMapRefreshSnapshot)) { return false; } Duration durationSinceLastForcedCollectionRoutingMapRefresh = Duration.between(lastCollectionRoutingMapRefreshSnapshot, Instant.now()); boolean returnValue = durationSinceLastForcedCollectionRoutingMapRefresh .compareTo(minDurationBeforeEnforcingCollectionRoutingMapRefresh) >= 0; return returnValue; } } }
Added
private void validateReplicaAddresses(String collectionRid, AddressInformation[] addresses) { checkNotNull(addresses, "Argument 'addresses' can not be null"); checkArgument(StringUtils.isNotEmpty(collectionRid), "Argument 'collectionRid' can not be null"); List<Uri> addressesNeedToValidation = new ArrayList<>(); for (AddressInformation address : addresses) { if (this.replicaValidationScopes.contains(address.getPhysicalUri().getHealthStatus())) { switch (address.getPhysicalUri().getHealthStatus()) { case UnhealthyPending: addressesNeedToValidation.add(0, address.getPhysicalUri()); break; case Unknown: addressesNeedToValidation.add(address.getPhysicalUri()); break; default: break; } } } if (addressesNeedToValidation.size() > 0) { logger.debug("Addresses to validate: [{}]", addressesNeedToValidation); this.openConnectionsHandler .openConnections(collectionRid, this.serviceEndpoint, addressesNeedToValidation) .subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC) .subscribe(); } }
break;
private void validateReplicaAddresses(String collectionRid, AddressInformation[] addresses) { checkNotNull(addresses, "Argument 'addresses' can not be null"); checkArgument(StringUtils.isNotEmpty(collectionRid), "Argument 'collectionRid' can not be null"); List<Uri> addressesNeedToValidation = new ArrayList<>(); for (AddressInformation address : addresses) { if (this.replicaValidationScopes.contains(address.getPhysicalUri().getHealthStatus())) { switch (address.getPhysicalUri().getHealthStatus()) { case UnhealthyPending: addressesNeedToValidation.add(0, address.getPhysicalUri()); break; case Unknown: addressesNeedToValidation.add(address.getPhysicalUri()); break; default: logger.debug("Validate replica status is not support for status " + address.getPhysicalUri().getHealthStatus()); break; } } } if (addressesNeedToValidation.size() > 0) { logger.debug("Addresses to validate: [{}]", addressesNeedToValidation); this.openConnectionsHandler .openConnections(collectionRid, this.serviceEndpoint, addressesNeedToValidation) .subscribeOn(CosmosSchedulers.OPEN_CONNECTIONS_BOUNDED_ELASTIC) .subscribe(); } }
class GatewayAddressCache implements IAddressCache { private static Duration minDurationBeforeEnforcingCollectionRoutingMapRefresh = Duration.ofSeconds(30); private final static Logger logger = LoggerFactory.getLogger(GatewayAddressCache.class); private final static String protocolFilterFormat = "%s eq %s"; private final static int DefaultBatchSize = 50; private final static int DefaultSuboptimalPartitionForceRefreshIntervalInSeconds = 600; private final DiagnosticsClientContext clientContext; private final String databaseFeedEntryUrl = PathsHelper.generatePath(ResourceType.Database, "", true); private final URI addressEndpoint; private final URI serviceEndpoint; private final AsyncCacheNonBlocking<PartitionKeyRangeIdentity, AddressInformation[]> serverPartitionAddressCache; private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> suboptimalServerPartitionTimestamps; private final long suboptimalPartitionForceRefreshIntervalInSeconds; private final String protocolScheme; private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap<String, String> defaultRequestHeaders; private final HttpClient httpClient; private volatile Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; private final ConcurrentHashMap<String, ForcedRefreshMetadata> lastForcedRefreshMap; private final GlobalEndpointManager globalEndpointManager; private IOpenConnectionsHandler openConnectionsHandler; private final ConnectionPolicy connectionPolicy; private final boolean replicaAddressValidationEnabled; private final Set<Uri.HealthStatus> replicaValidationScopes; public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this.clientContext = clientContext; try { this.addressEndpoint = new URL(serviceEndpoint.toURL(), Paths.ADDRESS_PATH_SEGMENT).toURI(); } catch (MalformedURLException | URISyntaxException e) { logger.error("serviceEndpoint {} is invalid", serviceEndpoint, e); assert false; throw new IllegalStateException(e); } this.serviceEndpoint = serviceEndpoint; this.tokenProvider = tokenProvider; this.serverPartitionAddressCache = new AsyncCacheNonBlocking<>(); this.suboptimalServerPartitionTimestamps = new ConcurrentHashMap<>(); this.suboptimalMasterPartitionTimestamp = Instant.MAX; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.protocolScheme = protocol.scheme(); this.protocolFilter = String.format(GatewayAddressCache.protocolFilterFormat, Constants.Properties.PROTOCOL, this.protocolScheme); this.httpClient = httpClient; if (userAgent == null) { userAgent = new UserAgentContainer(); } defaultRequestHeaders = new HashMap<>(); defaultRequestHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); if(apiType != null) { defaultRequestHeaders.put(HttpConstants.HttpHeaders.API_TYPE, apiType.toString()); } defaultRequestHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.defaultRequestHeaders.put( HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); this.lastForcedRefreshMap = new ConcurrentHashMap<>(); this.globalEndpointManager = globalEndpointManager; this.openConnectionsHandler = openConnectionsHandler; this.connectionPolicy = connectionPolicy; this.replicaAddressValidationEnabled = Configs.isReplicaAddressValidationEnabled(); this.replicaValidationScopes = ConcurrentHashMap.newKeySet(); if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.UnhealthyPending); } } public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this(clientContext, serviceEndpoint, protocol, tokenProvider, userAgent, httpClient, DefaultSuboptimalPartitionForceRefreshIntervalInSeconds, apiType, globalEndpointManager, connectionPolicy, openConnectionsHandler); } @Override public Mono<Utils.ValueHolder<AddressInformation[]>> tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); logger.debug("PartitionKeyRangeIdentity {}, forceRefreshPartitionAddresses {}", partitionKeyRangeIdentity, forceRefreshPartitionAddresses); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties) .map(partitionKeyRangeIdentityPair -> new Utils.ValueHolder<>(partitionKeyRangeIdentityPair.getRight())); } evaluateCollectionRoutingMapRefreshForServerPartition( request, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); if (suboptimalServerPartitionTimestamp != null) { logger.debug("suboptimalServerPartitionTimestamp is {}", suboptimalServerPartitionTimestamp); boolean forceRefreshDueToSuboptimalPartitionReplicaSet = Duration.between(suboptimalServerPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds; if (forceRefreshDueToSuboptimalPartitionReplicaSet) { Instant newValue = this.suboptimalServerPartitionTimestamps.computeIfPresent(partitionKeyRangeIdentity, (key, oldVal) -> { logger.debug("key = {}, oldValue = {}", key, oldVal); if (suboptimalServerPartitionTimestamp.equals(oldVal)) { return Instant.MAX; } else { return oldVal; } }); logger.debug("newValue is {}", newValue); if (!suboptimalServerPartitionTimestamp.equals(newValue)) { logger.debug("setting forceRefreshPartitionAddresses to true"); forceRefreshPartitionAddresses = true; } } } final boolean forceRefreshPartitionAddressesModified = forceRefreshPartitionAddresses; if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } Mono<Utils.ValueHolder<AddressInformation[]>> addressesObs = this.serverPartitionAddressCache .getAsync( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId( request, partitionKeyRangeIdentity, forceRefreshPartitionAddressesModified, cachedAddresses), cachedAddresses -> { for (Uri failedEndpoints : request.requestContext.getFailedEndpoints()) { failedEndpoints.setUnhealthy(); } return forceRefreshPartitionAddressesModified; }) .map(Utils.ValueHolder::new); return addressesObs .map(addressesValueHolder -> { if (notAllReplicasAvailable(addressesValueHolder.v)) { if (logger.isDebugEnabled()) { logger.debug("not all replicas available {}", JavaStreamUtils.info(addressesValueHolder.v)); } this.suboptimalServerPartitionTimestamps.putIfAbsent(partitionKeyRangeIdentity, Instant.now()); } if (Arrays .stream(addressesValueHolder.v) .anyMatch(addressInformation -> addressInformation.getPhysicalUri().shouldRefreshHealthStatus())) { logger.debug("refresh cache due to address uri in unhealthy status for pkRangeId {}", partitionKeyRangeIdentity.getPartitionKeyRangeId()); this.serverPartitionAddressCache.refresh( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId(request, partitionKeyRangeIdentity, true, cachedAddresses)); } return addressesValueHolder; }) .onErrorResume(ex -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(ex); CosmosException dce = Utils.as(unwrappedException, CosmosException.class); if (dce == null) { logger.error("unexpected failure", ex); if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } return Mono.error(unwrappedException); } else { logger.debug("tryGetAddresses dce", dce); if (Exceptions.isNotFound(dce) || Exceptions.isGone(dce) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); logger.debug("tryGetAddresses: inner onErrorResumeNext return null", dce); return Mono.just(new Utils.ValueHolder<>(null)); } return Mono.error(unwrappedException); } }); } @Override public void setOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler) { this.openConnectionsHandler = openConnectionsHandler; } public Mono<List<Address>> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid, JavaStreamUtils.toString(partitionKeyRangeIds, ",")); } request.setAddressRefresh(true, forceRefresh); String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true); HashMap<String, String> addressQuery = new HashMap<>(); addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = null; try { token = this.tokenProvider.getUserAuthorizationToken( collectionRid, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } catch (UnauthorizedException e) { if (logger.isDebugEnabled()) { logger.debug("User doesn't have resource token for collection rid {}", collectionRid); } } if (token == null && request.getIsNameBased()) { String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress()); token = this.tokenProvider.getUserAuthorizationToken( collectionAltLink, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } token = HttpUtils.urlEncode(token); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart( request, targetEndpoint, forceRefresh, request.forceCollectionRoutingMapRefresh); headers.put(HttpConstants.HttpHeaders.ACTIVITY_ID, identifier); HttpHeaders httpHeaders = new HttpHeaders(headers); Instant addressCallStartTime = Instant.now(); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(httpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.SERVER_ADDRESS_LOOKUP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync deserializes result"); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } public void dispose() { } private Mono<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map<String, Object> properties) { logger.debug("resolveMasterAsync forceRefresh: {}", forceRefresh); Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || (masterAddressAndRangeInitial != null && notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { Mono<List<Address>> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, databaseFeedEntryUrl, forceRefresh, false, properties); return masterReplicaAddressesObs.map( masterAddresses -> { Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeRes = this.toPartitionAddressAndRange("", masterAddresses); this.masterPartitionAddressCache = masterAddressAndRangeRes; if (notAllReplicasAvailable(masterAddressAndRangeRes.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } else { this.suboptimalMasterPartitionTimestamp = Instant.MAX; } return masterPartitionAddressCache; }) .doOnError( e -> { this.suboptimalMasterPartitionTimestamp = Instant.MAX; }); } else { if (notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } return Mono.just(masterAddressAndRangeInitial); } } private void evaluateCollectionRoutingMapRefreshForServerPartition( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); if (forceRefreshPartitionAddresses) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); if (request.forceCollectionRoutingMapRefresh) { forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else if (forcedRefreshMetadata.shouldIncludeCollectionRoutingMapRefresh(pkRangeIdentity)) { request.forceCollectionRoutingMapRefresh = true; forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else { forcedRefreshMetadata.signalPartitionAddressOnlyRefresh(pkRangeIdentity); } } else if (request.forceCollectionRoutingMapRefresh) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, false); } logger.debug("evaluateCollectionRoutingMapRefreshForServerPartition collectionRid {}, partitionKeyRangeId {}," + " " + "forceRefreshPartitionAddresses {}, forceCollectionRoutingMapRefresh {}", collectionRid, partitionKeyRangeId, forceRefreshPartitionAddresses, request.forceCollectionRoutingMapRefresh); } private void validatePkRangeIdentity(PartitionKeyRangeIdentity pkRangeIdentity) { Utils.checkNotNullOrThrow(pkRangeIdentity, "pkRangeId", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getCollectionRid(), "pkRangeId.getCollectionRid()", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getPartitionKeyRangeId(), "pkRangeId.getPartitionKeyRangeId()", ""); } private Mono<AddressInformation[]> getAddressesForRangeId( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefresh, AddressInformation[] cachedAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); logger.debug( "getAddressesForRangeId collectionRid {}, partitionKeyRangeId {}, forceRefresh {}", collectionRid, partitionKeyRangeId, forceRefresh); Mono<List<Address>> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> addressInfos = addressResponse.map( addresses -> { if (logger.isDebugEnabled()) { logger.debug("addresses from getServerAddressesViaGatewayAsync in getAddressesForRangeId {}", JavaStreamUtils.info(addresses)); } return addresses .stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList()); }); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> result = addressInfos .map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); return result .flatMap( list -> { if (logger.isDebugEnabled()) { logger.debug("getAddressesForRangeId flatMap got result {}", JavaStreamUtils.info(list)); } if (list.isEmpty()) { String errorMessage = String.format( RMResources.PartitionKeyRangeNotFound, partitionKeyRangeId, collectionRid); PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); return Mono.error(e); } else { AddressInformation[] mergedAddresses = this.mergeAddresses(list.get(0).getRight(), cachedAddresses); for (AddressInformation address : mergedAddresses) { address.getPhysicalUri().setRefreshed(); } if (this.replicaAddressValidationEnabled) { this.validateReplicaAddresses(collectionRid, mergedAddresses); } return Mono.just(mergedAddresses); } }) .doOnError(e -> logger.debug("getAddressesForRangeId", e)); } public Mono<List<Address>> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, String entryUrl, boolean forceRefresh, boolean useMasterCollectionResolver, Map<String, Object> properties) { logger.debug("getMasterAddressesViaGatewayAsync " + "resourceType {}, " + "resourceAddress {}, " + "entryUrl {}, " + "forceRefresh {}, " + "useMasterCollectionResolver {}", resourceType, resourceAddress, entryUrl, forceRefresh, useMasterCollectionResolver ); request.setAddressRefresh(true, forceRefresh); HashMap<String, String> queryParameters = new HashMap<>(); queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (useMasterCollectionResolver) { headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, "true"); } if(request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = this.tokenProvider.getUserAuthorizationToken( resourceAddress, resourceType, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, properties); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart( request, targetEndpoint, true, true); headers.put(HttpConstants.HttpHeaders.ACTIVITY_ID, identifier); HttpHeaders defaultHttpHeaders = new HttpHeaders(headers); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), defaultHttpHeaders); Instant addressCallStartTime = Instant.now(); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(defaultHttpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, this.clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.MASTER_ADDRESS_LOOK_UP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } /*** * merge the new addresses get back from gateway with the cached addresses. * If the address is being returned from gateway again, then keep using the cached addressInformation object * If it is a new address being returned, then use the new addressInformation object. * * @param newAddresses the latest addresses being returned from gateway. * @param cachedAddresses the cached addresses. * * @return the merged addresses. */ private AddressInformation[] mergeAddresses(AddressInformation[] newAddresses, AddressInformation[] cachedAddresses) { checkNotNull(newAddresses, "Argument 'newAddresses' should not be null"); if (cachedAddresses == null) { return newAddresses; } List<AddressInformation> mergedAddresses = new ArrayList<>(); Map<Uri, List<AddressInformation>> cachedAddressMap = Arrays .stream(cachedAddresses) .collect(Collectors.groupingBy(AddressInformation::getPhysicalUri)); for (AddressInformation newAddress : newAddresses) { boolean useCachedAddress = false; if (cachedAddressMap.containsKey(newAddress.getPhysicalUri())) { for (AddressInformation cachedAddress : cachedAddressMap.get(newAddress.getPhysicalUri())) { if (newAddress.getProtocol() == cachedAddress.getProtocol() && newAddress.isPublic() == cachedAddress.isPublic() && newAddress.isPrimary() == cachedAddress.isPrimary()) { useCachedAddress = true; mergedAddresses.add(cachedAddress); break; } } } if (!useCachedAddress) { mergedAddresses.add(newAddress); } } return mergedAddresses.toArray(new AddressInformation[mergedAddresses.size()]); } private Pair<PartitionKeyRangeIdentity, AddressInformation[]> toPartitionAddressAndRange(String collectionRid, List<Address> addresses) { if (logger.isDebugEnabled()) { logger.debug("toPartitionAddressAndRange"); } Address address = addresses.get(0); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, address.getParitionKeyRangeId()); AddressInformation[] addressInfos = addresses .stream() .map(addr -> GatewayAddressCache.toAddressInformation(addr)) .collect(Collectors.toList()) .toArray(new AddressInformation[addresses.size()]); return Pair.of(partitionKeyRangeIdentity, addressInfos); } private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.isPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } public Flux<OpenConnectionResponse> openConnectionsAndInitCaches( DocumentCollection collection, List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) { checkNotNull(collection, "Argument 'collection' should not be null"); checkNotNull(partitionKeyRangeIdentities, "Argument 'partitionKeyRangeIdentities' should not be null"); if (logger.isDebugEnabled()) { logger.debug( "openConnectionsAndInitCaches collection: {}, partitionKeyRangeIdentities: {}", collection.getResourceId(), JavaStreamUtils.toString(partitionKeyRangeIdentities, ",")); } if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.Unknown); } List<Flux<List<Address>>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this.clientContext, OperationType.Read, collection.getResourceId(), ResourceType.DocumentCollection, Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; endIndex = Math.min(endIndex, partitionKeyRangeIdentities.size()); tasks.add( this.getServerAddressesViaGatewayWithRetry( request, collection.getResourceId(), partitionKeyRangeIdentities .subList(i, endIndex) .stream() .map(PartitionKeyRangeIdentity::getPartitionKeyRangeId) .collect(Collectors.toList()), false).flux()); } return Flux.concat(tasks) .flatMap(list -> { List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream().map(addresses -> toPartitionAddressAndRange(collection.getResourceId(), addresses)) .collect(Collectors.toList()); return Flux.fromIterable(addressInfos) .flatMap( addressInfo -> { this.serverPartitionAddressCache.set(addressInfo.getLeft(), addressInfo.getRight()); if (this.openConnectionsHandler != null) { return this.openConnectionsHandler.openConnections( collection.getResourceId(), this.serviceEndpoint, Arrays .stream(addressInfo.getRight()) .map(addressInformation -> addressInformation.getPhysicalUri()) .collect(Collectors.toList())); } logger.info("OpenConnectionHandler is null, can not open connections"); return Flux.empty(); }, Configs.getCPUCnt() * 10, Configs.getCPUCnt() * 3); }); } private Mono<List<Address>> getServerAddressesViaGatewayWithRetry( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { OpenConnectionAndInitCachesRetryPolicy openConnectionAndInitCachesRetryPolicy = new OpenConnectionAndInitCachesRetryPolicy(this.connectionPolicy.getThrottlingRetryOptions()); return BackoffRetryUtility.executeRetry( () -> this.getServerAddressesViaGatewayAsync(request, collectionRid, partitionKeyRangeIds, forceRefresh), openConnectionAndInitCachesRetryPolicy); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart( RxDocumentServiceRequest request, URI targetEndpointUrl, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { if (request.requestContext.cosmosDiagnostics != null) { return BridgeInternal.recordAddressResolutionStart( request.requestContext.cosmosDiagnostics, targetEndpointUrl, forceRefresh, forceCollectionRoutingMapRefresh); } return null; } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier, String errorMessage) { if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosDiagnostics, identifier, errorMessage); } } private static class ForcedRefreshMetadata { private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> lastPartitionAddressOnlyRefresh; private Instant lastCollectionRoutingMapRefresh; public ForcedRefreshMetadata() { lastPartitionAddressOnlyRefresh = new ConcurrentHashMap<>(); lastCollectionRoutingMapRefresh = Instant.now(); } public void signalCollectionRoutingMapRefresh( PartitionKeyRangeIdentity pk, boolean forcePartitionAddressRefresh) { Instant nowSnapshot = Instant.now(); if (forcePartitionAddressRefresh) { lastPartitionAddressOnlyRefresh.put(pk, nowSnapshot); } lastCollectionRoutingMapRefresh = nowSnapshot; } public void signalPartitionAddressOnlyRefresh(PartitionKeyRangeIdentity pk) { lastPartitionAddressOnlyRefresh.put(pk, Instant.now()); } public boolean shouldIncludeCollectionRoutingMapRefresh(PartitionKeyRangeIdentity pk) { Instant lastPartitionAddressRefreshSnapshot = lastPartitionAddressOnlyRefresh.get(pk); Instant lastCollectionRoutingMapRefreshSnapshot = lastCollectionRoutingMapRefresh; if (lastPartitionAddressRefreshSnapshot == null || !lastPartitionAddressRefreshSnapshot.isAfter(lastCollectionRoutingMapRefreshSnapshot)) { return false; } Duration durationSinceLastForcedCollectionRoutingMapRefresh = Duration.between(lastCollectionRoutingMapRefreshSnapshot, Instant.now()); boolean returnValue = durationSinceLastForcedCollectionRoutingMapRefresh .compareTo(minDurationBeforeEnforcingCollectionRoutingMapRefresh) >= 0; return returnValue; } } }
class GatewayAddressCache implements IAddressCache { private static Duration minDurationBeforeEnforcingCollectionRoutingMapRefresh = Duration.ofSeconds(30); private final static Logger logger = LoggerFactory.getLogger(GatewayAddressCache.class); private final static String protocolFilterFormat = "%s eq %s"; private final static int DefaultBatchSize = 50; private final static int DefaultSuboptimalPartitionForceRefreshIntervalInSeconds = 600; private final DiagnosticsClientContext clientContext; private final String databaseFeedEntryUrl = PathsHelper.generatePath(ResourceType.Database, "", true); private final URI addressEndpoint; private final URI serviceEndpoint; private final AsyncCacheNonBlocking<PartitionKeyRangeIdentity, AddressInformation[]> serverPartitionAddressCache; private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> suboptimalServerPartitionTimestamps; private final long suboptimalPartitionForceRefreshIntervalInSeconds; private final String protocolScheme; private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap<String, String> defaultRequestHeaders; private final HttpClient httpClient; private volatile Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; private final ConcurrentHashMap<String, ForcedRefreshMetadata> lastForcedRefreshMap; private final GlobalEndpointManager globalEndpointManager; private IOpenConnectionsHandler openConnectionsHandler; private final ConnectionPolicy connectionPolicy; private final boolean replicaAddressValidationEnabled; private final Set<Uri.HealthStatus> replicaValidationScopes; public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this.clientContext = clientContext; try { this.addressEndpoint = new URL(serviceEndpoint.toURL(), Paths.ADDRESS_PATH_SEGMENT).toURI(); } catch (MalformedURLException | URISyntaxException e) { logger.error("serviceEndpoint {} is invalid", serviceEndpoint, e); assert false; throw new IllegalStateException(e); } this.serviceEndpoint = serviceEndpoint; this.tokenProvider = tokenProvider; this.serverPartitionAddressCache = new AsyncCacheNonBlocking<>(); this.suboptimalServerPartitionTimestamps = new ConcurrentHashMap<>(); this.suboptimalMasterPartitionTimestamp = Instant.MAX; this.suboptimalPartitionForceRefreshIntervalInSeconds = suboptimalPartitionForceRefreshIntervalInSeconds; this.protocolScheme = protocol.scheme(); this.protocolFilter = String.format(GatewayAddressCache.protocolFilterFormat, Constants.Properties.PROTOCOL, this.protocolScheme); this.httpClient = httpClient; if (userAgent == null) { userAgent = new UserAgentContainer(); } defaultRequestHeaders = new HashMap<>(); defaultRequestHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); if(apiType != null) { defaultRequestHeaders.put(HttpConstants.HttpHeaders.API_TYPE, apiType.toString()); } defaultRequestHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.defaultRequestHeaders.put( HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); this.lastForcedRefreshMap = new ConcurrentHashMap<>(); this.globalEndpointManager = globalEndpointManager; this.openConnectionsHandler = openConnectionsHandler; this.connectionPolicy = connectionPolicy; this.replicaAddressValidationEnabled = Configs.isReplicaAddressValidationEnabled(); this.replicaValidationScopes = ConcurrentHashMap.newKeySet(); if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.UnhealthyPending); } } public GatewayAddressCache( DiagnosticsClientContext clientContext, URI serviceEndpoint, Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, HttpClient httpClient, ApiType apiType, GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy, IOpenConnectionsHandler openConnectionsHandler) { this(clientContext, serviceEndpoint, protocol, tokenProvider, userAgent, httpClient, DefaultSuboptimalPartitionForceRefreshIntervalInSeconds, apiType, globalEndpointManager, connectionPolicy, openConnectionsHandler); } @Override public Mono<Utils.ValueHolder<AddressInformation[]>> tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); logger.debug("PartitionKeyRangeIdentity {}, forceRefreshPartitionAddresses {}", partitionKeyRangeIdentity, forceRefreshPartitionAddresses); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties) .map(partitionKeyRangeIdentityPair -> new Utils.ValueHolder<>(partitionKeyRangeIdentityPair.getRight())); } evaluateCollectionRoutingMapRefreshForServerPartition( request, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); if (suboptimalServerPartitionTimestamp != null) { logger.debug("suboptimalServerPartitionTimestamp is {}", suboptimalServerPartitionTimestamp); boolean forceRefreshDueToSuboptimalPartitionReplicaSet = Duration.between(suboptimalServerPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds; if (forceRefreshDueToSuboptimalPartitionReplicaSet) { Instant newValue = this.suboptimalServerPartitionTimestamps.computeIfPresent(partitionKeyRangeIdentity, (key, oldVal) -> { logger.debug("key = {}, oldValue = {}", key, oldVal); if (suboptimalServerPartitionTimestamp.equals(oldVal)) { return Instant.MAX; } else { return oldVal; } }); logger.debug("newValue is {}", newValue); if (!suboptimalServerPartitionTimestamp.equals(newValue)) { logger.debug("setting forceRefreshPartitionAddresses to true"); forceRefreshPartitionAddresses = true; } } } final boolean forceRefreshPartitionAddressesModified = forceRefreshPartitionAddresses; if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } Mono<Utils.ValueHolder<AddressInformation[]>> addressesObs = this.serverPartitionAddressCache .getAsync( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId( request, partitionKeyRangeIdentity, forceRefreshPartitionAddressesModified, cachedAddresses), cachedAddresses -> { for (Uri failedEndpoints : request.requestContext.getFailedEndpoints()) { failedEndpoints.setUnhealthy(); } return forceRefreshPartitionAddressesModified; }) .map(Utils.ValueHolder::new); return addressesObs .map(addressesValueHolder -> { if (notAllReplicasAvailable(addressesValueHolder.v)) { if (logger.isDebugEnabled()) { logger.debug("not all replicas available {}", JavaStreamUtils.info(addressesValueHolder.v)); } this.suboptimalServerPartitionTimestamps.putIfAbsent(partitionKeyRangeIdentity, Instant.now()); } if (Arrays .stream(addressesValueHolder.v) .anyMatch(addressInformation -> addressInformation.getPhysicalUri().shouldRefreshHealthStatus())) { logger.debug("refresh cache due to address uri in unhealthy status for pkRangeId {}", partitionKeyRangeIdentity.getPartitionKeyRangeId()); this.serverPartitionAddressCache.refresh( partitionKeyRangeIdentity, cachedAddresses -> this.getAddressesForRangeId(request, partitionKeyRangeIdentity, true, cachedAddresses)); } return addressesValueHolder; }) .onErrorResume(ex -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(ex); CosmosException dce = Utils.as(unwrappedException, CosmosException.class); if (dce == null) { logger.error("unexpected failure", ex); if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } return Mono.error(unwrappedException); } else { logger.debug("tryGetAddresses dce", dce); if (Exceptions.isNotFound(dce) || Exceptions.isGone(dce) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); logger.debug("tryGetAddresses: inner onErrorResumeNext return null", dce); return Mono.just(new Utils.ValueHolder<>(null)); } return Mono.error(unwrappedException); } }); } @Override public void setOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler) { this.openConnectionsHandler = openConnectionsHandler; } public Mono<List<Address>> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync collectionRid {}, partitionKeyRangeIds {}", collectionRid, JavaStreamUtils.toString(partitionKeyRangeIds, ",")); } request.setAddressRefresh(true, forceRefresh); String entryUrl = PathsHelper.generatePath(ResourceType.Document, collectionRid, true); HashMap<String, String> addressQuery = new HashMap<>(); addressQuery.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } addressQuery.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = null; try { token = this.tokenProvider.getUserAuthorizationToken( collectionRid, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } catch (UnauthorizedException e) { if (logger.isDebugEnabled()) { logger.debug("User doesn't have resource token for collection rid {}", collectionRid); } } if (token == null && request.getIsNameBased()) { String collectionAltLink = PathsHelper.getCollectionPath(request.getResourceAddress()); token = this.tokenProvider.getUserAuthorizationToken( collectionAltLink, ResourceType.Document, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, request.properties); } token = HttpUtils.urlEncode(token); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart( request, targetEndpoint, forceRefresh, request.forceCollectionRoutingMapRefresh); headers.put(HttpConstants.HttpHeaders.ACTIVITY_ID, identifier); HttpHeaders httpHeaders = new HttpHeaders(headers); Instant addressCallStartTime = Instant.now(); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(httpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.SERVER_ADDRESS_LOOKUP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } if (logger.isDebugEnabled()) { logger.debug("getServerAddressesViaGatewayAsync deserializes result"); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } public void dispose() { } private Mono<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map<String, Object> properties) { logger.debug("resolveMasterAsync forceRefresh: {}", forceRefresh); Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || (masterAddressAndRangeInitial != null && notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { Mono<List<Address>> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, databaseFeedEntryUrl, forceRefresh, false, properties); return masterReplicaAddressesObs.map( masterAddresses -> { Pair<PartitionKeyRangeIdentity, AddressInformation[]> masterAddressAndRangeRes = this.toPartitionAddressAndRange("", masterAddresses); this.masterPartitionAddressCache = masterAddressAndRangeRes; if (notAllReplicasAvailable(masterAddressAndRangeRes.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } else { this.suboptimalMasterPartitionTimestamp = Instant.MAX; } return masterPartitionAddressCache; }) .doOnError( e -> { this.suboptimalMasterPartitionTimestamp = Instant.MAX; }); } else { if (notAllReplicasAvailable(masterAddressAndRangeInitial.getRight()) && this.suboptimalMasterPartitionTimestamp.equals(Instant.MAX)) { this.suboptimalMasterPartitionTimestamp = Instant.now(); } return Mono.just(masterAddressAndRangeInitial); } } private void evaluateCollectionRoutingMapRefreshForServerPartition( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefreshPartitionAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); if (forceRefreshPartitionAddresses) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); if (request.forceCollectionRoutingMapRefresh) { forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else if (forcedRefreshMetadata.shouldIncludeCollectionRoutingMapRefresh(pkRangeIdentity)) { request.forceCollectionRoutingMapRefresh = true; forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, true); } else { forcedRefreshMetadata.signalPartitionAddressOnlyRefresh(pkRangeIdentity); } } else if (request.forceCollectionRoutingMapRefresh) { ForcedRefreshMetadata forcedRefreshMetadata = this.lastForcedRefreshMap.computeIfAbsent( collectionRid, (colRid) -> new ForcedRefreshMetadata()); forcedRefreshMetadata.signalCollectionRoutingMapRefresh( pkRangeIdentity, false); } logger.debug("evaluateCollectionRoutingMapRefreshForServerPartition collectionRid {}, partitionKeyRangeId {}," + " " + "forceRefreshPartitionAddresses {}, forceCollectionRoutingMapRefresh {}", collectionRid, partitionKeyRangeId, forceRefreshPartitionAddresses, request.forceCollectionRoutingMapRefresh); } private void validatePkRangeIdentity(PartitionKeyRangeIdentity pkRangeIdentity) { Utils.checkNotNullOrThrow(pkRangeIdentity, "pkRangeId", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getCollectionRid(), "pkRangeId.getCollectionRid()", ""); Utils.checkNotNullOrThrow( pkRangeIdentity.getPartitionKeyRangeId(), "pkRangeId.getPartitionKeyRangeId()", ""); } private Mono<AddressInformation[]> getAddressesForRangeId( RxDocumentServiceRequest request, PartitionKeyRangeIdentity pkRangeIdentity, boolean forceRefresh, AddressInformation[] cachedAddresses) { Utils.checkNotNullOrThrow(request, "request", ""); validatePkRangeIdentity(pkRangeIdentity); String collectionRid = pkRangeIdentity.getCollectionRid(); String partitionKeyRangeId = pkRangeIdentity.getPartitionKeyRangeId(); logger.debug( "getAddressesForRangeId collectionRid {}, partitionKeyRangeId {}, forceRefresh {}", collectionRid, partitionKeyRangeId, forceRefresh); Mono<List<Address>> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> addressInfos = addressResponse.map( addresses -> { if (logger.isDebugEnabled()) { logger.debug("addresses from getServerAddressesViaGatewayAsync in getAddressesForRangeId {}", JavaStreamUtils.info(addresses)); } return addresses .stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList()); }); Mono<List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>>> result = addressInfos .map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); return result .flatMap( list -> { if (logger.isDebugEnabled()) { logger.debug("getAddressesForRangeId flatMap got result {}", JavaStreamUtils.info(list)); } if (list.isEmpty()) { String errorMessage = String.format( RMResources.PartitionKeyRangeNotFound, partitionKeyRangeId, collectionRid); PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); return Mono.error(e); } else { AddressInformation[] mergedAddresses = this.mergeAddresses(list.get(0).getRight(), cachedAddresses); for (AddressInformation address : mergedAddresses) { address.getPhysicalUri().setRefreshed(); } if (this.replicaAddressValidationEnabled) { this.validateReplicaAddresses(collectionRid, mergedAddresses); } return Mono.just(mergedAddresses); } }) .doOnError(e -> logger.debug("getAddressesForRangeId", e)); } public Mono<List<Address>> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, String entryUrl, boolean forceRefresh, boolean useMasterCollectionResolver, Map<String, Object> properties) { logger.debug("getMasterAddressesViaGatewayAsync " + "resourceType {}, " + "resourceAddress {}, " + "entryUrl {}, " + "forceRefresh {}, " + "useMasterCollectionResolver {}", resourceType, resourceAddress, entryUrl, forceRefresh, useMasterCollectionResolver ); request.setAddressRefresh(true, forceRefresh); HashMap<String, String> queryParameters = new HashMap<>(); queryParameters.put(HttpConstants.QueryStrings.URL, HttpUtils.urlEncode(entryUrl)); HashMap<String, String> headers = new HashMap<>(defaultRequestHeaders); if (forceRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_REFRESH, "true"); } if (useMasterCollectionResolver) { headers.put(HttpConstants.HttpHeaders.USE_MASTER_COLLECTION_RESOLVER, "true"); } if(request.forceCollectionRoutingMapRefresh) { headers.put(HttpConstants.HttpHeaders.FORCE_COLLECTION_ROUTING_MAP_REFRESH, "true"); } queryParameters.put(HttpConstants.QueryStrings.FILTER, HttpUtils.urlEncode(this.protocolFilter)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { String token = this.tokenProvider.getUserAuthorizationToken( resourceAddress, resourceType, RequestVerb.GET, headers, AuthorizationTokenType.PrimaryMasterKey, properties); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); } URI targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart( request, targetEndpoint, true, true); headers.put(HttpConstants.HttpHeaders.ACTIVITY_ID, identifier); HttpHeaders defaultHttpHeaders = new HttpHeaders(headers); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint, targetEndpoint.getPort(), defaultHttpHeaders); Instant addressCallStartTime = Instant.now(); Mono<HttpResponse> httpResponseMono; if (tokenProvider.getAuthorizationTokenType() != AuthorizationTokenType.AadToken) { httpResponseMono = this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds())); } else { httpResponseMono = tokenProvider .populateAuthorizationHeader(defaultHttpHeaders) .flatMap(valueHttpHeaders -> this.httpClient.send(httpRequest, Duration.ofSeconds(Configs.getAddressRefreshResponseTimeoutInSeconds()))); } Mono<RxDocumentServiceResponse> dsrObs = HttpClientUtils.parseResponseAsync(request, this.clientContext, httpResponseMono, httpRequest); return dsrObs.map( dsr -> { MetadataDiagnosticsContext metadataDiagnosticsContext = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (metadataDiagnosticsContext != null) { Instant addressCallEndTime = Instant.now(); MetadataDiagnostics metaDataDiagnostic = new MetadataDiagnostics(addressCallStartTime, addressCallEndTime, MetadataType.MASTER_ADDRESS_LOOK_UP); metadataDiagnosticsContext.addMetaDataDiagnostic(metaDataDiagnostic); } logAddressResolutionEnd(request, identifier, null); return dsr.getQueryResponse(null, Address.class); }).onErrorResume(throwable -> { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); logAddressResolutionEnd(request, identifier, unwrappedException.toString()); if (!(unwrappedException instanceof Exception)) { logger.error("Unexpected failure {}", unwrappedException.getMessage(), unwrappedException); return Mono.error(unwrappedException); } Exception exception = (Exception) unwrappedException; CosmosException dce; if (!(exception instanceof CosmosException)) { logger.error("Network failure", exception); int statusCode = 0; if (WebExceptionUtility.isNetworkFailure(exception)) { if (WebExceptionUtility.isReadTimeoutException(exception)) { statusCode = HttpConstants.StatusCodes.REQUEST_TIMEOUT; } else { statusCode = HttpConstants.StatusCodes.SERVICE_UNAVAILABLE; } } dce = BridgeInternal.createCosmosException( request.requestContext.resourcePhysicalAddress, statusCode, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); } else { dce = (CosmosException) exception; } if (WebExceptionUtility.isNetworkFailure(dce)) { if (WebExceptionUtility.isReadTimeoutException(dce)) { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT); } else { BridgeInternal.setSubStatusCode(dce, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE); } } if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordGatewayResponse(request.requestContext.cosmosDiagnostics, request, dce, this.globalEndpointManager); } return Mono.error(dce); }); } /*** * merge the new addresses get back from gateway with the cached addresses. * If the address is being returned from gateway again, then keep using the cached addressInformation object * If it is a new address being returned, then use the new addressInformation object. * * @param newAddresses the latest addresses being returned from gateway. * @param cachedAddresses the cached addresses. * * @return the merged addresses. */ private AddressInformation[] mergeAddresses(AddressInformation[] newAddresses, AddressInformation[] cachedAddresses) { checkNotNull(newAddresses, "Argument 'newAddresses' should not be null"); if (cachedAddresses == null) { return newAddresses; } List<AddressInformation> mergedAddresses = new ArrayList<>(); Map<Uri, List<AddressInformation>> cachedAddressMap = Arrays .stream(cachedAddresses) .collect(Collectors.groupingBy(AddressInformation::getPhysicalUri)); for (AddressInformation newAddress : newAddresses) { boolean useCachedAddress = false; if (cachedAddressMap.containsKey(newAddress.getPhysicalUri())) { for (AddressInformation cachedAddress : cachedAddressMap.get(newAddress.getPhysicalUri())) { if (newAddress.getProtocol() == cachedAddress.getProtocol() && newAddress.isPublic() == cachedAddress.isPublic() && newAddress.isPrimary() == cachedAddress.isPrimary()) { useCachedAddress = true; mergedAddresses.add(cachedAddress); break; } } } if (!useCachedAddress) { mergedAddresses.add(newAddress); } } return mergedAddresses.toArray(new AddressInformation[mergedAddresses.size()]); } private Pair<PartitionKeyRangeIdentity, AddressInformation[]> toPartitionAddressAndRange(String collectionRid, List<Address> addresses) { if (logger.isDebugEnabled()) { logger.debug("toPartitionAddressAndRange"); } Address address = addresses.get(0); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, address.getParitionKeyRangeId()); AddressInformation[] addressInfos = addresses .stream() .map(addr -> GatewayAddressCache.toAddressInformation(addr)) .collect(Collectors.toList()) .toArray(new AddressInformation[addresses.size()]); return Pair.of(partitionKeyRangeIdentity, addressInfos); } private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.isPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } public Flux<OpenConnectionResponse> openConnectionsAndInitCaches( DocumentCollection collection, List<PartitionKeyRangeIdentity> partitionKeyRangeIdentities) { checkNotNull(collection, "Argument 'collection' should not be null"); checkNotNull(partitionKeyRangeIdentities, "Argument 'partitionKeyRangeIdentities' should not be null"); if (logger.isDebugEnabled()) { logger.debug( "openConnectionsAndInitCaches collection: {}, partitionKeyRangeIdentities: {}", collection.getResourceId(), JavaStreamUtils.toString(partitionKeyRangeIdentities, ",")); } if (this.replicaAddressValidationEnabled) { this.replicaValidationScopes.add(Uri.HealthStatus.Unknown); } List<Flux<List<Address>>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this.clientContext, OperationType.Read, collection.getResourceId(), ResourceType.DocumentCollection, Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; endIndex = Math.min(endIndex, partitionKeyRangeIdentities.size()); tasks.add( this.getServerAddressesViaGatewayWithRetry( request, collection.getResourceId(), partitionKeyRangeIdentities .subList(i, endIndex) .stream() .map(PartitionKeyRangeIdentity::getPartitionKeyRangeId) .collect(Collectors.toList()), false).flux()); } return Flux.concat(tasks) .flatMap(list -> { List<Pair<PartitionKeyRangeIdentity, AddressInformation[]>> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) .values() .stream().map(addresses -> toPartitionAddressAndRange(collection.getResourceId(), addresses)) .collect(Collectors.toList()); return Flux.fromIterable(addressInfos) .flatMap( addressInfo -> { this.serverPartitionAddressCache.set(addressInfo.getLeft(), addressInfo.getRight()); if (this.openConnectionsHandler != null) { return this.openConnectionsHandler.openConnections( collection.getResourceId(), this.serviceEndpoint, Arrays .stream(addressInfo.getRight()) .map(addressInformation -> addressInformation.getPhysicalUri()) .collect(Collectors.toList())); } logger.info("OpenConnectionHandler is null, can not open connections"); return Flux.empty(); }, Configs.getCPUCnt() * 10, Configs.getCPUCnt() * 3); }); } private Mono<List<Address>> getServerAddressesViaGatewayWithRetry( RxDocumentServiceRequest request, String collectionRid, List<String> partitionKeyRangeIds, boolean forceRefresh) { OpenConnectionAndInitCachesRetryPolicy openConnectionAndInitCachesRetryPolicy = new OpenConnectionAndInitCachesRetryPolicy(this.connectionPolicy.getThrottlingRetryOptions()); return BackoffRetryUtility.executeRetry( () -> this.getServerAddressesViaGatewayAsync(request, collectionRid, partitionKeyRangeIds, forceRefresh), openConnectionAndInitCachesRetryPolicy); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart( RxDocumentServiceRequest request, URI targetEndpointUrl, boolean forceRefresh, boolean forceCollectionRoutingMapRefresh) { if (request.requestContext.cosmosDiagnostics != null) { return BridgeInternal.recordAddressResolutionStart( request.requestContext.cosmosDiagnostics, targetEndpointUrl, forceRefresh, forceCollectionRoutingMapRefresh); } return null; } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier, String errorMessage) { if (request.requestContext.cosmosDiagnostics != null) { BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosDiagnostics, identifier, errorMessage); } } private static class ForcedRefreshMetadata { private final ConcurrentHashMap<PartitionKeyRangeIdentity, Instant> lastPartitionAddressOnlyRefresh; private Instant lastCollectionRoutingMapRefresh; public ForcedRefreshMetadata() { lastPartitionAddressOnlyRefresh = new ConcurrentHashMap<>(); lastCollectionRoutingMapRefresh = Instant.now(); } public void signalCollectionRoutingMapRefresh( PartitionKeyRangeIdentity pk, boolean forcePartitionAddressRefresh) { Instant nowSnapshot = Instant.now(); if (forcePartitionAddressRefresh) { lastPartitionAddressOnlyRefresh.put(pk, nowSnapshot); } lastCollectionRoutingMapRefresh = nowSnapshot; } public void signalPartitionAddressOnlyRefresh(PartitionKeyRangeIdentity pk) { lastPartitionAddressOnlyRefresh.put(pk, Instant.now()); } public boolean shouldIncludeCollectionRoutingMapRefresh(PartitionKeyRangeIdentity pk) { Instant lastPartitionAddressRefreshSnapshot = lastPartitionAddressOnlyRefresh.get(pk); Instant lastCollectionRoutingMapRefreshSnapshot = lastCollectionRoutingMapRefresh; if (lastPartitionAddressRefreshSnapshot == null || !lastPartitionAddressRefreshSnapshot.isAfter(lastCollectionRoutingMapRefreshSnapshot)) { return false; } Duration durationSinceLastForcedCollectionRoutingMapRefresh = Duration.between(lastCollectionRoutingMapRefreshSnapshot, Instant.now()); boolean returnValue = durationSinceLastForcedCollectionRoutingMapRefresh .compareTo(minDurationBeforeEnforcingCollectionRoutingMapRefresh) >= 0; return returnValue; } } }
should we also validate the cosmosDiagnostics here?
public void clientLevelEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosClientBuilder builder = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig) .credential(credential); try (CosmosAsyncClient cosmosAsyncClient = builder.buildAsyncClient()) { String dbname = "db_" + UUID.randomUUID(); String containerName = "container_" + UUID.randomUUID(); CosmosContainerProperties properties = new CosmosContainerProperties(containerName, "/mypk"); cosmosAsyncClient.createDatabaseIfNotExists(dbname).block(); cosmosAsyncClient.getDatabase(dbname) .createContainerIfNotExists(properties).block(); CosmosAsyncContainer container = cosmosAsyncClient.getDatabase(dbname) .getContainer(containerName); TestObject obj = new TestObject(UUID.randomUUID().toString(), "name123", 2, UUID.randomUUID().toString()); CosmosItemResponse response = container.createItem(obj).block(); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = container.readItem(obj.id, new PartitionKey(obj.mypk), TestObject.class); StepVerifier.create(cosmosItemResponseMono) .expectNextCount(1) .expectComplete() .verify(); injectFailure(container, FaultInjectionOperationType.READ_ITEM, null); verifyExpectError(cosmosItemResponseMono); String queryText = "select top 1 * from c"; SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(queryText); CosmosPagedFlux<TestObject> queryPagedFlux = container.queryItems(sqlQuerySpec, TestObject.class); StepVerifier.create(queryPagedFlux) .expectNextCount(1) .expectComplete() .verify(); injectFailure(container, FaultInjectionOperationType.QUERY_ITEM, null); StepVerifier.create(queryPagedFlux) .expectErrorMatches(throwable -> throwable instanceof RequestCancelledException) .verify(); CosmosItemRequestOptions options = new CosmosItemRequestOptions() .setCosmosEndToEndOperationLatencyPolicyConfig(CosmosEndToEndOperationLatencyPolicyConfig.DISABLED); cosmosItemResponseMono = container.readItem(obj.id, new PartitionKey(obj.mypk), options, TestObject.class); StepVerifier.create(cosmosItemResponseMono) .expectNextCount(1) .expectComplete() .verify(); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions() .setCosmosEndToEndOperationLatencyPolicyConfig(CosmosEndToEndOperationLatencyPolicyConfig.DISABLED); queryPagedFlux = container.queryItems(sqlQuerySpec, queryRequestOptions, TestObject.class); StepVerifier.create(queryPagedFlux) .expectNextCount(1) .expectComplete() .verify(); cosmosAsyncClient.getDatabase(dbname).delete().block(); } }
.expectErrorMatches(throwable -> throwable instanceof RequestCancelledException)
public void clientLevelEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosClientBuilder builder = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig) .credential(credential); try (CosmosAsyncClient cosmosAsyncClient = builder.buildAsyncClient()) { String dbname = "db_" + UUID.randomUUID(); String containerName = "container_" + UUID.randomUUID(); CosmosContainerProperties properties = new CosmosContainerProperties(containerName, "/mypk"); cosmosAsyncClient.createDatabaseIfNotExists(dbname).block(); cosmosAsyncClient.getDatabase(dbname) .createContainerIfNotExists(properties).block(); CosmosAsyncContainer container = cosmosAsyncClient.getDatabase(dbname) .getContainer(containerName); TestObject obj = new TestObject(UUID.randomUUID().toString(), "name123", 2, UUID.randomUUID().toString()); CosmosItemResponse response = container.createItem(obj).block(); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = container.readItem(obj.id, new PartitionKey(obj.mypk), TestObject.class); StepVerifier.create(cosmosItemResponseMono) .expectNextCount(1) .expectComplete() .verify(); injectFailure(container, FaultInjectionOperationType.READ_ITEM, null); verifyExpectError(cosmosItemResponseMono); String queryText = "select top 1 * from c"; SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(queryText); CosmosPagedFlux<TestObject> queryPagedFlux = container.queryItems(sqlQuerySpec, TestObject.class); StepVerifier.create(queryPagedFlux) .expectNextCount(1) .expectComplete() .verify(); injectFailure(container, FaultInjectionOperationType.QUERY_ITEM, null); StepVerifier.create(queryPagedFlux) .expectErrorMatches(throwable -> throwable instanceof OperationCancelledException) .verify(); CosmosItemRequestOptions options = new CosmosItemRequestOptions() .setCosmosEndToEndOperationLatencyPolicyConfig( new CosmosE2EOperationRetryPolicyConfigBuilder(Duration.ofSeconds(1)) .enable(false) .build()); cosmosItemResponseMono = container.readItem(obj.id, new PartitionKey(obj.mypk), options, TestObject.class); StepVerifier.create(cosmosItemResponseMono) .expectNextCount(1) .expectComplete() .verify(); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions() .setCosmosEndToEndOperationLatencyPolicyConfig( new CosmosE2EOperationRetryPolicyConfigBuilder(Duration.ofSeconds(1)) .enable(false) .build()); queryPagedFlux = container.queryItems(sqlQuerySpec, queryRequestOptions, TestObject.class); StepVerifier.create(queryPagedFlux) .expectNextCount(1) .expectComplete() .verify(); cosmosAsyncClient.getDatabase(dbname).delete().block(); } }
class EndToEndTimeOutValidationTests extends TestSuiteBase { private static final int DEFAULT_NUM_DOCUMENTS = 100; private static final int DEFAULT_PAGE_SIZE = 100; private CosmosAsyncContainer createdContainer; private final Random random; private final List<TestObject> createdDocuments = new ArrayList<>(); private final CosmosEndToEndOperationLatencyPolicyConfig endToEndOperationLatencyPolicyConfig; @Factory(dataProvider = "clientBuildersWithDirectTcpSession") public EndToEndTimeOutValidationTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); random = new Random(); endToEndOperationLatencyPolicyConfig = new CosmosEndToEndOperationLatencyPolicyConfigBuilder() .endToEndOperationTimeout(Duration.ofSeconds(1)) .build(); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT * 100) public void beforeClass() throws Exception { CosmosAsyncClient client = this.getClientBuilder().buildAsyncClient(); CosmosAsyncDatabase createdDatabase = getSharedCosmosDatabase(client); createdContainer = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdContainer); createdDocuments.addAll(this.insertDocuments(DEFAULT_NUM_DOCUMENTS, null, createdContainer)); } @Test(groups = {"simple"}, timeOut = 10000L) public void readItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject itemToRead = createdDocuments.get(random.nextInt(createdDocuments.size())); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.READ_ITEM, null); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.readItem(itemToRead.id, new PartitionKey(itemToRead.mypk), options, TestObject.class); verifyExpectError(cosmosItemResponseMono); rule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void createItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); FaultInjectionRule faultInjectionRule = injectFailure(createdContainer, FaultInjectionOperationType.CREATE_ITEM, null); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.createItem(inputObject, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); faultInjectionRule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void replaceItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); createdContainer.createItem(inputObject, new PartitionKey(inputObject.mypk), options).block(); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.REPLACE_ITEM, null); inputObject.setName("replaceName"); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.replaceItem(inputObject, inputObject.id, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); rule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void upsertItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.UPSERT_ITEM, null); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.upsertItem(inputObject, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); rule.disable(); } private static void verifyExpectError(Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono) { StepVerifier.create(cosmosItemResponseMono) .expectErrorMatches(throwable -> throwable instanceof RequestCancelledException) .verify(); } @Test(groups = {"simple"}, timeOut = 10000L) public void queryItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosEndToEndOperationLatencyPolicyConfig endToEndOperationLatencyPolicyConfig = new CosmosEndToEndOperationLatencyPolicyConfigBuilder() .endToEndOperationTimeout(Duration.ofSeconds(1)) .build(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject itemToQuery = createdDocuments.get(random.nextInt(createdDocuments.size())); String queryText = "select top 1 * from c"; SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(queryText); injectFailure(createdContainer, FaultInjectionOperationType.QUERY_ITEM, null); CosmosPagedFlux<TestObject> queryPagedFlux = createdContainer.queryItems(sqlQuerySpec, options, TestObject.class); StepVerifier.create(queryPagedFlux) .expectErrorMatches(throwable -> throwable instanceof RequestCancelledException) .verify(); } @Test(groups = {"simple"}, timeOut = 10000L) private FaultInjectionRule injectFailure( CosmosAsyncContainer container, FaultInjectionOperationType operationType, Boolean suppressServiceRequests) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofMillis(1500)) .times(1); if (suppressServiceRequests != null) { faultInjectionResultBuilder.suppressServiceRequests(suppressServiceRequests); } IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(operationType) .connectionType(FaultInjectionConnectionType.DIRECT) .build(); FaultInjectionRule rule = new FaultInjectionRuleBuilder("InjectedResponseDelay") .condition(condition) .result(result) .build(); FaultInjectorProvider injectorProvider = (FaultInjectorProvider) container .getOrConfigureFaultInjectorProvider(() -> new FaultInjectorProvider(container)); injectorProvider.configureFaultInjectionRules(Arrays.asList(rule)).block(); return rule; } private TestObject getDocumentDefinition(String documentId, String partitionKey) { int randInt = random.nextInt(DEFAULT_NUM_DOCUMENTS / 2); TestObject doc = new TestObject(documentId, "name" + randInt, randInt, partitionKey); return doc; } private List<TestObject> insertDocuments(int documentCount, List<String> partitionKeys, CosmosAsyncContainer container) { List<TestObject> documentsToInsert = new ArrayList<>(); for (int i = 0; i < documentCount; i++) { documentsToInsert.add( getDocumentDefinition( UUID.randomUUID().toString(), partitionKeys == null ? UUID.randomUUID().toString() : partitionKeys.get(random.nextInt(partitionKeys.size())))); } List<TestObject> documentInserted = bulkInsertBlocking(container, documentsToInsert); waitIfNeededForReplicasToCatchUp(this.getClientBuilder()); return documentInserted; } static class TestObject { String id; String name; int prop; String mypk; String constantProp = "constantProp"; public TestObject() { } public TestObject(String id, String name, int prop, String mypk) { this.id = id; this.name = name; this.prop = prop; this.mypk = mypk; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getProp() { return prop; } public void setProp(final int prop) { this.prop = prop; } public String getMypk() { return mypk; } public void setMypk(String mypk) { this.mypk = mypk; } public String getConstantProp() { return constantProp; } } }
class EndToEndTimeOutValidationTests extends TestSuiteBase { private static final int DEFAULT_NUM_DOCUMENTS = 100; private static final int DEFAULT_PAGE_SIZE = 100; private CosmosAsyncContainer createdContainer; private final Random random; private final List<TestObject> createdDocuments = new ArrayList<>(); private final CosmosE2EOperationRetryPolicyConfig endToEndOperationLatencyPolicyConfig; @Factory(dataProvider = "clientBuildersWithDirectTcpSession") public EndToEndTimeOutValidationTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); random = new Random(); endToEndOperationLatencyPolicyConfig = new CosmosE2EOperationRetryPolicyConfigBuilder(Duration.ofSeconds(1)) .build(); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT * 100) public void beforeClass() throws Exception { CosmosAsyncClient client = this.getClientBuilder().buildAsyncClient(); CosmosAsyncDatabase createdDatabase = getSharedCosmosDatabase(client); createdContainer = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdContainer); createdDocuments.addAll(this.insertDocuments(DEFAULT_NUM_DOCUMENTS, null, createdContainer)); } @Test(groups = {"simple"}, timeOut = 10000L) public void readItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject itemToRead = createdDocuments.get(random.nextInt(createdDocuments.size())); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.READ_ITEM, null); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.readItem(itemToRead.id, new PartitionKey(itemToRead.mypk), options, TestObject.class); verifyExpectError(cosmosItemResponseMono); rule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void createItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); FaultInjectionRule faultInjectionRule = injectFailure(createdContainer, FaultInjectionOperationType.CREATE_ITEM, null); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.createItem(inputObject, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); faultInjectionRule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void replaceItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); createdContainer.createItem(inputObject, new PartitionKey(inputObject.mypk), options).block(); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.REPLACE_ITEM, null); inputObject.setName("replaceName"); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.replaceItem(inputObject, inputObject.id, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); rule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void upsertItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.UPSERT_ITEM, null); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.upsertItem(inputObject, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); rule.disable(); } private static void verifyExpectError(Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono) { StepVerifier.create(cosmosItemResponseMono) .expectErrorMatches(throwable -> throwable instanceof OperationCancelledException) .verify(); } @Test(groups = {"simple"}, timeOut = 10000L) public void queryItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosE2EOperationRetryPolicyConfig endToEndOperationLatencyPolicyConfig = new CosmosE2EOperationRetryPolicyConfigBuilder(Duration.ofSeconds(1)) .build(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject itemToQuery = createdDocuments.get(random.nextInt(createdDocuments.size())); String queryText = "select top 1 * from c"; SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(queryText); injectFailure(createdContainer, FaultInjectionOperationType.QUERY_ITEM, null); CosmosPagedFlux<TestObject> queryPagedFlux = createdContainer.queryItems(sqlQuerySpec, options, TestObject.class); StepVerifier.create(queryPagedFlux) .expectErrorMatches(throwable -> throwable instanceof OperationCancelledException && ((OperationCancelledException) throwable).getSubStatusCode() == HttpConstants.SubStatusCodes.CLIENT_OPERATION_TIMEOUT) .verify(); } @Test(groups = {"simple"}, timeOut = 10000L) private FaultInjectionRule injectFailure( CosmosAsyncContainer container, FaultInjectionOperationType operationType, Boolean suppressServiceRequests) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofMillis(1500)) .times(1); if (suppressServiceRequests != null) { faultInjectionResultBuilder.suppressServiceRequests(suppressServiceRequests); } IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(operationType) .connectionType(FaultInjectionConnectionType.DIRECT) .build(); FaultInjectionRule rule = new FaultInjectionRuleBuilder("InjectedResponseDelay") .condition(condition) .result(result) .build(); FaultInjectorProvider injectorProvider = (FaultInjectorProvider) container .getOrConfigureFaultInjectorProvider(() -> new FaultInjectorProvider(container)); injectorProvider.configureFaultInjectionRules(Arrays.asList(rule)).block(); return rule; } private TestObject getDocumentDefinition(String documentId, String partitionKey) { int randInt = random.nextInt(DEFAULT_NUM_DOCUMENTS / 2); TestObject doc = new TestObject(documentId, "name" + randInt, randInt, partitionKey); return doc; } private List<TestObject> insertDocuments(int documentCount, List<String> partitionKeys, CosmosAsyncContainer container) { List<TestObject> documentsToInsert = new ArrayList<>(); for (int i = 0; i < documentCount; i++) { documentsToInsert.add( getDocumentDefinition( UUID.randomUUID().toString(), partitionKeys == null ? UUID.randomUUID().toString() : partitionKeys.get(random.nextInt(partitionKeys.size())))); } List<TestObject> documentInserted = bulkInsertBlocking(container, documentsToInsert); waitIfNeededForReplicasToCatchUp(this.getClientBuilder()); return documentInserted; } static class TestObject { String id; String name; int prop; String mypk; String constantProp = "constantProp"; public TestObject() { } public TestObject(String id, String name, int prop, String mypk) { this.id = id; this.name = name; this.prop = prop; this.mypk = mypk; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getProp() { return prop; } public void setProp(final int prop) { this.prop = prop; } public String getMypk() { return mypk; } public void setMypk(String mypk) { this.mypk = mypk; } public String getConstantProp() { return constantProp; } } }
unwrap throwable for safety.
private static Throwable getCancellationException(RxDocumentServiceRequest request, Throwable throwable) { if (throwable instanceof TimeoutException) { CosmosException exception = new RequestCancelledException(); exception.setStackTrace(throwable.getStackTrace()); return BridgeInternal.setCosmosDiagnostics(exception, request.requestContext.cosmosDiagnostics); } return throwable; }
if (throwable instanceof TimeoutException) {
private static Throwable getCancellationException(RxDocumentServiceRequest request, Throwable throwable) { Throwable unwrappedException = reactor.core.Exceptions.unwrap(throwable); if (unwrappedException instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); return BridgeInternal.setCosmosDiagnostics(exception, request.requestContext.cosmosDiagnostics); } return throwable; }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final Map<String, Integer> clientMap = new ConcurrentHashMap<>(); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final static Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxGatewayStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private final Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private final ApiType apiType; private final CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig; private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; private final CosmosClientTelemetryConfig clientTelemetryConfig; private final String clientCorrelationId; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig) { this( serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosEndToEndOperationLatencyPolicyConfig); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosEndToEndOperationLatencyPolicyConfig cosmosEndToEndOperationLatencyPolicyConfig) { assert(clientTelemetryConfig != null); Boolean clientTelemetryEnabled = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .isSendClientTelemetryToServiceEnabled(clientTelemetryConfig); assert(clientTelemetryEnabled != null); activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.clientCorrelationId = Strings.isNullOrWhiteSpace(clientCorrelationId) ? String.format("%05d",this.clientId): clientCorrelationId; clientMap.put(serviceEndpoint.toString(), clientMap.getOrDefault(serviceEndpoint.toString(), 0) + 1); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withClientMap(clientMap); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); this.cosmosEndToEndOperationLatencyPolicyConfig = cosmosEndToEndOperationLatencyPolicyConfig; logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; this.clientTelemetryConfig = clientTelemetryConfig; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { return BridgeInternal.createCosmosDiagnostics(this); } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { (this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); (this.gatewayProxy).setCollectionCache(this.collectionCache); (this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); (this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry( this, null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.configs, this.clientTelemetryConfig, this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager ); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations ); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public String getClientCorrelationId() { return this.clientCorrelationId; } @Override public String getMachineId() { if (this.diagnosticsClientConfig == null) { return null; } return this.diagnosticsClientConfig.getMachineId(); } @Override public String getUserAgent() { return this.userAgentContainer.getUserAgent(); } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getCorrelationActivityId(options); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId), invalidPartitionExceptionRetryPolicy); } private <T> Flux<FeedResponse<T>> createQueryInternal( String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; Flux<FeedResponse<T>> feedResponseFlux = iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = options.getCosmosEndToEndOperationLatencyPolicyConfig() != null ? options.getCosmosEndToEndOperationLatencyPolicyConfig() : this.cosmosEndToEndOperationLatencyPolicyConfig; if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return feedResponseFlux .timeout(endToEndPolicyConfig.getEndToEndOperationTimeout()) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException exception = new RequestCancelledException(); exception.setStackTrace(throwable.getStackTrace()); return exception; } return throwable; }); } return feedResponseFlux; }, Queues.SMALL_BUFFER_SIZE, 1); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, CosmosQueryRequestOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if(options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null && options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } public static PartitionKeyInternal extractPartitionKeyValueFromDocument( JsonSerializable document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { switch (partitionKeyDefinition.getKind()) { case HASH: String path = partitionKeyDefinition.getPaths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts); if (value == null || value.getClass() == ObjectNode.class) { value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } break; case MULTI_HASH: Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()]; for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){ String partitionPath = partitionKeyDefinition.getPaths().get(pathIter); List<String> partitionPathParts = PathParser.getPathParts(partitionPath); partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts); } return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false); default: throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind()); } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); String trackingId = null; if (options != null) { trackingId = options.getTrackingId(); } ByteBuffer content = InternalObjectNode.serializeJsonToByteBuffer(document, mapper, trackingId); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Document, path, requestHeaders, options, content); if (operationType.isWriteOperation() && options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } this.populateCapabilitiesHeader(request); if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private void populateCapabilitiesHeader(RxDocumentServiceRequest request) { if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES)) { request .getHeaders() .put(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); } } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> { CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(options); Mono<RxDocumentServiceResponse> rxDocumentServiceResponseMono = create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return rxDocumentServiceResponseMono .timeout(endToEndPolicyConfig.getEndToEndOperationTimeout()) .onErrorMap(throwable -> getCancellationException(request, throwable)); } return rxDocumentServiceResponseMono; }); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance); } private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert); Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> { CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(options); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .timeout(endToEndPolicyConfig.getEndToEndOperationTimeout()) .onErrorMap(throwable -> getCancellationException(request, throwable)); } return upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)); }); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); if (options != null) { String trackingId = options.getTrackingId(); if (trackingId != null && !trackingId.isEmpty()) { document.set(Constants.Properties.TRACKING_ID, trackingId); } } ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs.flatMap(req -> { Mono<ResourceResponse<Document>> resourceResponseMono = replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class)); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(options); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return resourceResponseMono .timeout(endToEndPolicyConfig.getEndToEndOperationTimeout()) .onErrorMap(throwable -> getCancellationException(request, throwable)); } return resourceResponseMono; }); } private CosmosEndToEndOperationLatencyPolicyConfig getEndToEndOperationLatencyPolicyConfig(RequestOptions options) { CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = (options != null && options.getCosmosEndToEndLatencyPolicyConfig() != null) ? options.getCosmosEndToEndLatencyPolicyConfig() : this.cosmosEndToEndOperationLatencyPolicyConfig; return endToEndPolicyConfig; } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs.flatMap(req -> patch(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs); return requestObs.flatMap(req -> this .delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); CosmosEndToEndOperationLatencyPolicyConfig endToEndPolicyConfig = options.getCosmosEndToEndLatencyPolicyConfig() != null ? options.getCosmosEndToEndLatencyPolicyConfig() : this.cosmosEndToEndOperationLatencyPolicyConfig; return requestObs.flatMap(req -> { if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)) .timeout(endToEndPolicyConfig.getEndToEndOperationTimeout()) .onErrorMap(throwable -> getCancellationException(request, throwable)); } return this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, CosmosQueryRequestOptions options, Class<T> klass) { String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } itemIdentityList .forEach(itemIdentity -> { if (pkDefinition.getKind().equals(PartitionKind.MULTI_HASH) && ModelBridgeInternal.getPartitionKeyInternal(itemIdentity.getPartitionKey()) .getComponents().size() != pkDefinition.getPaths().size()) { throw new IllegalArgumentException(RMResources.PartitionKeyMismatch); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); Flux<FeedResponse<Document>> pointReads = createPointReadOperations( partitionRangeItemKeyMap, resourceLink, options, klass); Flux<FeedResponse<Document>> queries = createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)); return Flux.merge(pointReads, queries) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); Collection<ClientSideRequestStatistics> aggregateRequestStatistics = new DistinctClientSideRequestStatisticsCollection(); double requestCharge = 0; for (FeedResponse<Document> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList())); aggregateRequestStatistics.addAll(diagnosticsAccessor.getClientSideRequestStatistics(page.getCosmosDiagnostics())); } CosmosDiagnostics aggregatedDiagnostics = BridgeInternal.createCosmosDiagnostics(aggregatedQueryMetrics); diagnosticsAccessor.addClientSideDiagnosticsToFeed( aggregatedDiagnostics, aggregateRequestStatistics); headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponseWithQueryMetrics( finalList, headers, aggregatedQueryMetrics, null, false, false, aggregatedDiagnostics); return frp; }); }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); String partitionKeySelector = createPkSelector(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; List<CosmosItemIdentity> cosmosItemIdentityList = entry.getValue(); if (cosmosItemIdentityList.size() > 1) { if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(cosmosItemIdentityList, partitionKeySelector); } else if (partitionKeyDefinition.getKind().equals(PartitionKind.MULTI_HASH)) { sqlQuerySpec = createReadManyQuerySpecMultiHash(entry.getValue(), partitionKeyDefinition); } else { sqlQuerySpec = createReadManyQuerySpec(cosmosItemIdentityList, partitionKeySelector); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame( List<CosmosItemIdentity> idPartitionKeyPairList, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); if (!Objects.equals(idValue, pkValue)) { continue; } parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkParamName = "@param" + (2 * i); parameters.add(new SqlParameter(pkParamName, pkValue)); String idValue = itemIdentity.getId(); String idParamName = "@param" + (2 * i + 1); parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpecMultiHash( List<CosmosItemIdentity> itemIdentities, PartitionKeyDefinition partitionKeyDefinition) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); int paramCount = 0; for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkValueString = (String) pkValue; List<List<String>> partitionKeyParams = new ArrayList<>(); List<String> paths = partitionKeyDefinition.getPaths(); int pathCount = 0; for (String subPartitionKey: pkValueString.split("=")) { String pkParamName = "@param" + paramCount; partitionKeyParams.add(Arrays.asList(paths.get(pathCount), pkParamName)); parameters.add(new SqlParameter(pkParamName, subPartitionKey)); paramCount++; pathCount++; } String idValue = itemIdentity.getId(); String idParamName = "@param" + paramCount; paramCount++; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); for (List<String> pkParam: partitionKeyParams) { queryStringBuilder.append(" AND "); queryStringBuilder.append(" c."); queryStringBuilder.append(pkParam.get(0).substring(1)); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParam.get(1)); } queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.joining()); } private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { if (rangeQueryMap.isEmpty()) { return Flux.empty(); } UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum); return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); } private <T> Flux<FeedResponse<Document>> createPointReadOperations( Map<PartitionKeyRange, List<CosmosItemIdentity>> singleItemPartitionRequestMap, String resourceLink, CosmosQueryRequestOptions queryRequestOptions, Class<T> klass ) { return Flux.fromIterable(singleItemPartitionRequestMap.values()) .flatMap(cosmosItemIdentityList -> { if (cosmosItemIdentityList.size() == 1) { CosmosItemIdentity firstIdentity = cosmosItemIdentityList.get(0); RequestOptions requestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(queryRequestOptions); requestOptions.setPartitionKey(firstIdentity.getPartitionKey()); return this.readDocument((resourceLink + firstIdentity.getId()), requestOptions); } return Mono.empty(); }) .flatMap(resourceResponse -> { CosmosItemResponse<T> cosmosItemResponse = ModelBridgeInternal.createCosmosAsyncItemResponse(resourceResponse, klass, getItemDeserializer()); FeedResponse<Document> feedResponse = ModelBridgeInternal.createFeedResponse( Arrays.asList(InternalObjectNode.fromObject(cosmosItemResponse.getItem())), cosmosItemResponse.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosItemResponse.getDiagnostics()))); return Mono.just(feedResponse); }); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, CosmosQueryRequestOptions options, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options, classOfT); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); String pkSelector = createPkSelector(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); final CosmosQueryRequestOptions effectiveOptions = ModelBridgeInternal.createQueryRequestOptions(options); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId); }); }, invalidPartitionExceptionRetryPolicy); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, CosmosQueryRequestOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> readFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new CosmosQueryRequestOptions(); } Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options); int maxPageSize = maxItemCount != null ? maxItemCount : -1; final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options; DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage( response, ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getItemFactoryMethod(finalCosmosQueryRequestOptions, klass), klass)), retryPolicy); return Paginator.getPaginatedQueryResultAsObservable( options, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } @Override public GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } @Override public AddressSelector getAddressSelector() { return new AddressSelector(this.addressResolver, this.configs.getProtocol()); } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.useGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); this.storeModel.enableThroughputControl(throughputControlStore); } this.throughputControlStore.enableThroughputControlGroup(group, throughputQueryMono); } @Override public Flux<OpenConnectionResponse> openConnectionsAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig) { return this.storeModel.openConnectionsAndInitCaches(proactiveContainerInitConfig); } @Override public ConsistencyLevel getDefaultConsistencyLevelOfAccount() { return this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } /*** * Configure fault injector provider. * * @param injectorProvider the fault injector provider. */ @Override public void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) { checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null"); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.DIRECT) { this.storeModel.configureFaultInjectorProvider(injectorProvider); } else { throw new IllegalArgumentException("configureFaultInjectorProvider is not supported for gateway mode"); } } private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey); String pkParamName = "@pkValue"; parameters.add(new SqlParameter(pkParamName, pkValue)); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) { logger.debug("getFeedRange collectionLink=[{}]", collectionLink); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } }
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider, CpuMemoryListener, DiagnosticsClientContext { private final static ImplementationBridgeHelpers.CosmosDiagnosticsHelper.CosmosDiagnosticsAccessor diagnosticsAccessor = ImplementationBridgeHelpers.CosmosDiagnosticsHelper.getCosmosDiagnosticsAccessor(); private static final String tempMachineId = "uuid:" + UUID.randomUUID(); private static final AtomicInteger activeClientsCnt = new AtomicInteger(0); private static final Map<String, Integer> clientMap = new ConcurrentHashMap<>(); private static final AtomicInteger clientIdGenerator = new AtomicInteger(0); private static final Range<String> RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES = new Range<>( PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); private static final String DUMMY_SQL_QUERY = "this is dummy and only used in creating " + "ParallelDocumentQueryExecutioncontext, but not used"; private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final ItemDeserializer itemDeserializer = new ItemDeserializer.JsonDeserializer(); private final static Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEndpoint; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel consistencyLevel; private final BaseAuthorizationTokenProvider authorizationTokenProvider; private final UserAgentContainer userAgentContainer; private final boolean hasAuthKeyResourceToken; private final Configs configs; private final boolean connectionSharingAcrossClientsEnabled; private AzureKeyCredential credential; private final TokenCredential tokenCredential; private String[] tokenCredentialScopes; private SimpleTokenCache tokenCredentialCache; private CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver; AuthorizationTokenType authorizationTokenType; private SessionContainer sessionContainer; private String firstResourceTokenFromPermissionFeed = StringUtils.EMPTY; private RxClientCollectionCache collectionCache; private RxGatewayStoreModel gatewayProxy; private RxStoreModel storeModel; private GlobalAddressResolver addressResolver; private RxPartitionKeyRangeCache partitionKeyRangeCache; private Map<String, List<PartitionKeyAndResourceTokenPair>> resourceTokensMap; private final boolean contentResponseOnWriteEnabled; private final Map<String, PartitionedQueryExecutionInfo> queryPlanCache; private final AtomicBoolean closed = new AtomicBoolean(false); private final int clientId; private ClientTelemetry clientTelemetry; private final ApiType apiType; private final CosmosE2EOperationRetryPolicyConfig cosmosE2EOperationRetryPolicyConfig; private IRetryPolicyFactory resetSessionTokenRetryPolicy; /** * Compatibility mode: Allows to specify compatibility mode used by client when * making query requests. Should be removed when application/sql is no longer * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private HttpClient reactorHttpClient; private Function<HttpClient, HttpClient> httpClientInterceptor; private volatile boolean useMultipleWriteLocations; private StoreClientFactory storeClientFactory; private GatewayServiceConfigurationReader gatewayConfigurationReader; private final DiagnosticsClientConfig diagnosticsClientConfig; private final AtomicBoolean throughputControlEnabled; private ThroughputControlStore throughputControlStore; private final CosmosClientTelemetryConfig clientTelemetryConfig; private final String clientCorrelationId; public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosE2EOperationRetryPolicyConfig cosmosE2EOperationRetryPolicyConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, null, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosE2EOperationRetryPolicyConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, CosmosAuthorizationTokenResolver cosmosAuthorizationTokenResolver, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverride, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosE2EOperationRetryPolicyConfig cosmosE2EOperationRetryPolicyConfig) { this( serviceEndpoint, masterKeyOrResourceToken, permissionFeed, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverride, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosE2EOperationRetryPolicyConfig); this.cosmosAuthorizationTokenResolver = cosmosAuthorizationTokenResolver; } private RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, List<Permission> permissionFeed, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosE2EOperationRetryPolicyConfig cosmosE2EOperationRetryPolicyConfig) { this( serviceEndpoint, masterKeyOrResourceToken, connectionPolicy, consistencyLevel, configs, credential, tokenCredential, sessionCapturingOverrideEnabled, connectionSharingAcrossClientsEnabled, contentResponseOnWriteEnabled, metadataCachesSnapshot, apiType, clientTelemetryConfig, clientCorrelationId, cosmosE2EOperationRetryPolicyConfig); if (permissionFeed != null && permissionFeed.size() > 0) { this.resourceTokensMap = new HashMap<>(); for (Permission permission : permissionFeed) { String[] segments = StringUtils.split(permission.getResourceLink(), Constants.Properties.PATH_SEPARATOR.charAt(0)); if (segments.length <= 0) { throw new IllegalArgumentException("resourceLink"); } List<PartitionKeyAndResourceTokenPair> partitionKeyAndResourceTokenPairs = null; PathInfo pathInfo = new PathInfo(false, StringUtils.EMPTY, StringUtils.EMPTY, false); if (!PathsHelper.tryParsePathSegments(permission.getResourceLink(), pathInfo, null)) { throw new IllegalArgumentException(permission.getResourceLink()); } partitionKeyAndResourceTokenPairs = resourceTokensMap.get(pathInfo.resourceIdOrFullName); if (partitionKeyAndResourceTokenPairs == null) { partitionKeyAndResourceTokenPairs = new ArrayList<>(); this.resourceTokensMap.put(pathInfo.resourceIdOrFullName, partitionKeyAndResourceTokenPairs); } PartitionKey partitionKey = permission.getResourcePartitionKey(); partitionKeyAndResourceTokenPairs.add(new PartitionKeyAndResourceTokenPair( partitionKey != null ? BridgeInternal.getPartitionKeyInternal(partitionKey) : PartitionKeyInternal.Empty, permission.getToken())); logger.debug("Initializing resource token map , with map key [{}] , partition key [{}] and resource token [{}]", pathInfo.resourceIdOrFullName, partitionKey != null ? partitionKey.toString() : null, permission.getToken()); } if(this.resourceTokensMap.isEmpty()) { throw new IllegalArgumentException("permissionFeed"); } String firstToken = permissionFeed.get(0).getToken(); if(ResourceTokenAuthorizationHelper.isResourceToken(firstToken)) { this.firstResourceTokenFromPermissionFeed = firstToken; } } } RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs, AzureKeyCredential credential, TokenCredential tokenCredential, boolean sessionCapturingOverrideEnabled, boolean connectionSharingAcrossClientsEnabled, boolean contentResponseOnWriteEnabled, CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, ApiType apiType, CosmosClientTelemetryConfig clientTelemetryConfig, String clientCorrelationId, CosmosE2EOperationRetryPolicyConfig cosmosE2EOperationRetryPolicyConfig) { assert(clientTelemetryConfig != null); Boolean clientTelemetryEnabled = ImplementationBridgeHelpers .CosmosClientTelemetryConfigHelper .getCosmosClientTelemetryConfigAccessor() .isSendClientTelemetryToServiceEnabled(clientTelemetryConfig); assert(clientTelemetryEnabled != null); activeClientsCnt.incrementAndGet(); this.clientId = clientIdGenerator.incrementAndGet(); this.clientCorrelationId = Strings.isNullOrWhiteSpace(clientCorrelationId) ? String.format("%05d",this.clientId): clientCorrelationId; clientMap.put(serviceEndpoint.toString(), clientMap.getOrDefault(serviceEndpoint.toString(), 0) + 1); this.diagnosticsClientConfig = new DiagnosticsClientConfig(); this.diagnosticsClientConfig.withClientId(this.clientId); this.diagnosticsClientConfig.withActiveClientCounter(activeClientsCnt); this.diagnosticsClientConfig.withClientMap(clientMap); this.diagnosticsClientConfig.withConnectionSharingAcrossClientsEnabled(connectionSharingAcrossClientsEnabled); this.diagnosticsClientConfig.withConsistency(consistencyLevel); this.throughputControlEnabled = new AtomicBoolean(false); this.cosmosE2EOperationRetryPolicyConfig = cosmosE2EOperationRetryPolicyConfig; logger.info( "Initializing DocumentClient [{}] with" + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", this.clientId, serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); try { this.connectionSharingAcrossClientsEnabled = connectionSharingAcrossClientsEnabled; this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; this.serviceEndpoint = serviceEndpoint; this.credential = credential; this.tokenCredential = tokenCredential; this.contentResponseOnWriteEnabled = contentResponseOnWriteEnabled; this.authorizationTokenType = AuthorizationTokenType.Invalid; if (this.credential != null) { hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else if (masterKeyOrResourceToken != null && ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.authorizationTokenProvider = null; hasAuthKeyResourceToken = true; this.authorizationTokenType = AuthorizationTokenType.ResourceToken; } else if(masterKeyOrResourceToken != null && !ResourceTokenAuthorizationHelper.isResourceToken(masterKeyOrResourceToken)) { this.credential = new AzureKeyCredential(this.masterKeyOrResourceToken); hasAuthKeyResourceToken = false; this.authorizationTokenType = AuthorizationTokenType.PrimaryMasterKey; this.authorizationTokenProvider = new BaseAuthorizationTokenProvider(this.credential); } else { hasAuthKeyResourceToken = false; this.authorizationTokenProvider = null; if (tokenCredential != null) { this.tokenCredentialScopes = new String[] { serviceEndpoint.getScheme() + ": }; this.tokenCredentialCache = new SimpleTokenCache(() -> this.tokenCredential .getToken(new TokenRequestContext().addScopes(this.tokenCredentialScopes))); this.authorizationTokenType = AuthorizationTokenType.AadToken; } } if (connectionPolicy != null) { this.connectionPolicy = connectionPolicy; } else { this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); } this.diagnosticsClientConfig.withConnectionMode(this.getConnectionPolicy().getConnectionMode()); this.diagnosticsClientConfig.withMultipleWriteRegionsEnabled(this.connectionPolicy.isMultipleWriteRegionsEnabled()); this.diagnosticsClientConfig.withEndpointDiscoveryEnabled(this.connectionPolicy.isEndpointDiscoveryEnabled()); this.diagnosticsClientConfig.withPreferredRegions(this.connectionPolicy.getPreferredRegions()); this.diagnosticsClientConfig.withMachineId(tempMachineId); boolean disableSessionCapturing = (ConsistencyLevel.SESSION != consistencyLevel && !sessionCapturingOverrideEnabled); this.sessionContainer = new SessionContainer(this.serviceEndpoint.getHost(), disableSessionCapturing); this.consistencyLevel = consistencyLevel; this.userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } this.httpClientInterceptor = null; this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this, this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; CpuMemoryMonitor.register(this); this.queryPlanCache = new ConcurrentHashMap<>(); this.apiType = apiType; this.clientTelemetryConfig = clientTelemetryConfig; } catch (RuntimeException e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } @Override public DiagnosticsClientConfig getConfig() { return diagnosticsClientConfig; } @Override public CosmosDiagnostics createDiagnostics() { return BridgeInternal.createCosmosDiagnostics(this); } private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); if (databaseAccount == null) { logger.error("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: throw new RuntimeException("Client initialization failed." + " Check if the endpoint is reachable and if your auth token is valid. More info: https: } this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); } private void updateGatewayProxy() { (this.gatewayProxy).setGatewayServiceConfigurationReader(this.gatewayConfigurationReader); (this.gatewayProxy).setCollectionCache(this.collectionCache); (this.gatewayProxy).setPartitionKeyRangeCache(this.partitionKeyRangeCache); (this.gatewayProxy).setUseMultipleWriteLocations(this.useMultipleWriteLocations); } public void init(CosmosClientMetadataCachesSnapshot metadataCachesSnapshot, Function<HttpClient, HttpClient> httpClientInterceptor) { try { this.httpClientInterceptor = httpClientInterceptor; if (httpClientInterceptor != null) { this.reactorHttpClient = httpClientInterceptor.apply(httpClient()); } this.gatewayProxy = createRxGatewayProxy(this.sessionContainer, this.consistencyLevel, this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, this.reactorHttpClient, this.apiType); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); if (metadataCachesSnapshot != null) { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy, metadataCachesSnapshot.getCollectionInfoByNameCache(), metadataCachesSnapshot.getCollectionInfoByIdCache() ); } else { this.collectionCache = new RxClientCollectionCache(this, this.sessionContainer, this.gatewayProxy, this, this.retryPolicy); } this.resetSessionTokenRetryPolicy = new ResetSessionTokenRetryPolicyFactory(this.sessionContainer, this.collectionCache, this.retryPolicy); this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); updateGatewayProxy(); clientTelemetry = new ClientTelemetry( this, null, UUID.randomUUID().toString(), ManagementFactory.getRuntimeMXBean().getName(), userAgentContainer.getUserAgent(), connectionPolicy.getConnectionMode(), globalEndpointManager.getLatestDatabaseAccount().getId(), null, null, this.configs, this.clientTelemetryConfig, this, this.connectionPolicy.getPreferredRegions()); clientTelemetry.init(); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); } this.retryPolicy.setRxCollectionCache(this.collectionCache); } catch (Exception e) { logger.error("unexpected failure in initializing client.", e); close(); throw e; } } public void serialize(CosmosClientMetadataCachesSnapshot state) { RxCollectionCache.serialize(state, this.collectionCache); } private void initializeDirectConnectivity() { this.addressResolver = new GlobalAddressResolver(this, this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, null, this.connectionPolicy, this.apiType); this.storeClientFactory = new StoreClientFactory( this.addressResolver, this.diagnosticsClientConfig, this.configs, this.connectionPolicy, this.userAgentContainer, this.connectionSharingAcrossClientsEnabled, this.clientTelemetry, this.globalEndpointManager); this.createStoreModel(true); } DatabaseAccountManagerInternal asDatabaseAccountManagerInternal() { return new DatabaseAccountManagerInternal() { @Override public URI getServiceEndpoint() { return RxDocumentClientImpl.this.getServiceEndpoint(); } @Override public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @Override public ConnectionPolicy getConnectionPolicy() { return RxDocumentClientImpl.this.getConnectionPolicy(); } }; } RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, ConsistencyLevel consistencyLevel, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, HttpClient httpClient, ApiType apiType) { return new RxGatewayStoreModel( this, sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, httpClient, apiType); } private HttpClient httpClient() { HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeout(this.connectionPolicy.getIdleHttpConnectionTimeout()) .withPoolSize(this.connectionPolicy.getMaxConnectionPoolSize()) .withProxy(this.connectionPolicy.getProxy()) .withNetworkRequestTimeout(this.connectionPolicy.getHttpNetworkRequestTimeout()); if (connectionSharingAcrossClientsEnabled) { return SharedGatewayHttpClient.getOrCreateInstance(httpClientConfig, diagnosticsClientConfig); } else { diagnosticsClientConfig.withGatewayHttpClientConfig(httpClientConfig.toDiagnosticsString()); return HttpClient.createFixed(httpClientConfig); } } private void createStoreModel(boolean subscribeRntbdStatus) { StoreClient storeClient = this.storeClientFactory.createStoreClient(this, this.addressResolver, this.sessionContainer, this.gatewayConfigurationReader, this, this.useMultipleWriteLocations); this.storeModel = new ServerStoreModel(storeClient); } @Override public URI getServiceEndpoint() { return this.serviceEndpoint; } @Override public ConnectionPolicy getConnectionPolicy() { return this.connectionPolicy; } @Override public boolean isContentResponseOnWriteEnabled() { return contentResponseOnWriteEnabled; } @Override public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } @Override public ClientTelemetry getClientTelemetry() { return this.clientTelemetry; } @Override public String getClientCorrelationId() { return this.clientCorrelationId; } @Override public String getMachineId() { if (this.diagnosticsClientConfig == null) { return null; } return this.diagnosticsClientConfig.getMachineId(); } @Override public String getUserAgent() { return this.userAgentContainer.getUserAgent(); } @Override public Mono<ResourceResponse<Database>> createDatabase(Database database, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> createDatabaseInternal(Database database, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { throw new IllegalArgumentException("Database"); } logger.debug("Creating a Database. id: [{}]", database.getId()); validateResource(database); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(database); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.DATABASE_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.Database, Paths.DATABASES_ROOT, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> deleteDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> deleteDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Deleting a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Database>> readDatabase(String databaseLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Database>> readDatabaseInternal(String databaseLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } logger.debug("Reading a Database. databaseLink: [{}]", databaseLink); String path = Utils.joinPath(databaseLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Database, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Database, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Database>> readDatabases(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } private String parentResourceLinkToQueryLink(String parentResourceLink, ResourceType resourceTypeEnum) { switch (resourceTypeEnum) { case Database: return Paths.DATABASES_ROOT; case DocumentCollection: return Utils.joinPath(parentResourceLink, Paths.COLLECTIONS_PATH_SEGMENT); case Document: return Utils.joinPath(parentResourceLink, Paths.DOCUMENTS_PATH_SEGMENT); case Offer: return Paths.OFFERS_ROOT; case User: return Utils.joinPath(parentResourceLink, Paths.USERS_PATH_SEGMENT); case ClientEncryptionKey: return Utils.joinPath(parentResourceLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); case Permission: return Utils.joinPath(parentResourceLink, Paths.PERMISSIONS_PATH_SEGMENT); case Attachment: return Utils.joinPath(parentResourceLink, Paths.ATTACHMENTS_PATH_SEGMENT); case StoredProcedure: return Utils.joinPath(parentResourceLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); case Trigger: return Utils.joinPath(parentResourceLink, Paths.TRIGGERS_PATH_SEGMENT); case UserDefinedFunction: return Utils.joinPath(parentResourceLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); case Conflict: return Utils.joinPath(parentResourceLink, Paths.CONFLICTS_PATH_SEGMENT); default: throw new IllegalArgumentException("resource type not supported"); } } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(CosmosQueryRequestOptions options) { if (options == null) { return null; } return ImplementationBridgeHelpers.CosmosQueryRequestOptionsHelper.getCosmosQueryRequestOptionsAccessor().getOperationContext(options); } private OperationContextAndListenerTuple getOperationContextAndListenerTuple(RequestOptions options) { if (options == null) { return null; } return options.getOperationContextAndListenerTuple(); } private <T> Flux<FeedResponse<T>> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum) { String resourceLink = parentResourceLinkToQueryLink(parentResourceLink, resourceTypeEnum); UUID correlationActivityIdOfRequestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getCorrelationActivityId(options); UUID correlationActivityId = correlationActivityIdOfRequestOptions != null ? correlationActivityIdOfRequestOptions : Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(options)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> createQueryInternal( resourceLink, sqlQuery, options, klass, resourceTypeEnum, queryClient, correlationActivityId), invalidPartitionExceptionRetryPolicy); } private <T> Flux<FeedResponse<T>> createQueryInternal( String resourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, IDocumentQueryClient queryClient, UUID activityId) { Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory .createDocumentQueryExecutionContextAsync(this, queryClient, resourceTypeEnum, klass, sqlQuery, options, resourceLink, false, activityId, Configs.isQueryPlanCachingEnabled(), queryPlanCache); AtomicBoolean isFirstResponse = new AtomicBoolean(true); return executionContext.flatMap(iDocumentQueryExecutionContext -> { QueryInfo queryInfo = null; if (iDocumentQueryExecutionContext instanceof PipelinedQueryExecutionContextBase) { queryInfo = ((PipelinedQueryExecutionContextBase<T>) iDocumentQueryExecutionContext).getQueryInfo(); } QueryInfo finalQueryInfo = queryInfo; Flux<FeedResponse<T>> feedResponseFlux = iDocumentQueryExecutionContext.executeAsync() .map(tFeedResponse -> { if (finalQueryInfo != null) { if (finalQueryInfo.hasSelectValue()) { ModelBridgeInternal .addQueryInfoToFeedResponse(tFeedResponse, finalQueryInfo); } if (isFirstResponse.compareAndSet(true, false)) { ModelBridgeInternal.addQueryPlanDiagnosticsContextToFeedResponse(tFeedResponse, finalQueryInfo.getQueryPlanDiagnosticsContext()); } } return tFeedResponse; }); RequestOptions requestOptions = options == null? null : ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(options); CosmosE2EOperationRetryPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(requestOptions); if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return getFeedResponseFluxWithTimeout(feedResponseFlux, endToEndPolicyConfig); } return feedResponseFlux; }, Queues.SMALL_BUFFER_SIZE, 1); } private static <T> Flux<FeedResponse<T>> getFeedResponseFluxWithTimeout(Flux<FeedResponse<T>> feedResponseFlux, CosmosE2EOperationRetryPolicyConfig endToEndPolicyConfig) { return feedResponseFlux .timeout(endToEndPolicyConfig.getEndToEndOperationTimeout()) .onErrorMap(throwable -> { if (throwable instanceof TimeoutException) { CosmosException exception = new OperationCancelledException(); exception.setStackTrace(throwable.getStackTrace()); return exception; } return throwable; }); } @Override public Flux<FeedResponse<Database>> queryDatabases(String query, CosmosQueryRequestOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Database>> queryDatabases(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override public Mono<ResourceResponse<DocumentCollection>> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, collection.getId()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Create); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Create, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> replaceCollection(DocumentCollection collection, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { throw new IllegalArgumentException("collection"); } logger.debug("Replacing a Collection. id: [{}]", collection.getId()); validateResource(collection); String path = Utils.joinPath(collection.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer byteBuffer = ModelBridgeInternal.serializeJsonToByteBuffer(collection); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.CONTAINER_SERIALIZATION); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.DocumentCollection, path, byteBuffer, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } }); } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<DocumentCollection>> deleteCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> deleteCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<RxDocumentServiceResponse> delete(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.DELETE) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> deleteAllItemsByPartitionKey(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> read(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } Mono<RxDocumentServiceResponse> readFeed(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> getStoreProxy(requestPopulated).processMessage(requestPopulated)); } private Mono<RxDocumentServiceResponse> query(RxDocumentServiceRequest request) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> this.getStoreProxy(requestPopulated).processMessage(requestPopulated) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } )); } @Override public Mono<ResourceResponse<DocumentCollection>> readCollection(String collectionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<DocumentCollection>> readCollectionInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Reading a Collection. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.DocumentCollection, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DocumentCollection, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, DocumentCollection.class)); } catch (Exception e) { logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<DocumentCollection>> readCollections(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.DocumentCollection, DocumentCollection.class, Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, String query, CosmosQueryRequestOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override public Flux<FeedResponse<DocumentCollection>> queryCollections(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } private static String serializeProcedureParams(List<Object> objectArray) { String[] stringArray = new String[objectArray.size()]; for (int i = 0; i < objectArray.size(); ++i) { Object object = objectArray.get(i); if (object instanceof JsonSerializable) { stringArray[i] = ModelBridgeInternal.toJsonFromJsonSerializable((JsonSerializable) object); } else { try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } } } return String.format("[%s]", StringUtils.join(stringArray, ",")); } private static void validateResource(Resource resource) { if (!StringUtils.isEmpty(resource.getId())) { if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || resource.getId().indexOf('?') != -1 || resource.getId().indexOf(' throw new IllegalArgumentException("Id contains illegal chars."); } if (resource.getId().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } } private Map<String, String> getRequestHeaders(RequestOptions options, ResourceType resourceType, OperationType operationType) { Map<String, String> headers = new HashMap<>(); if (this.useMultipleWriteLocations) { headers.put(HttpConstants.HttpHeaders.ALLOW_TENTATIVE_WRITES, Boolean.TRUE.toString()); } if (consistencyLevel != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { if (!this.contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } return headers; } Map<String, String> customOptions = options.getHeaders(); if (customOptions != null) { headers.putAll(customOptions); } boolean contentResponseOnWriteEnabled = this.contentResponseOnWriteEnabled; if (options.isContentResponseOnWriteEnabled() != null) { contentResponseOnWriteEnabled = options.isContentResponseOnWriteEnabled(); } if (!contentResponseOnWriteEnabled && resourceType.equals(ResourceType.Document) && operationType.isWriteOperation()) { headers.put(HttpConstants.HttpHeaders.PREFER, HttpConstants.HeaderValues.PREFER_RETURN_MINIMAL); } if (options.getIfMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getIfMatchETag()); } if(options.getIfNoneMatchETag() != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getIfNoneMatchETag()); } if (options.getConsistencyLevel() != null) { headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { String postTriggerInclude = StringUtils.join(options.getPostTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, postTriggerInclude); } if (options.getPreTriggerInclude() != null && options.getPreTriggerInclude().size() > 0) { String preTriggerInclude = StringUtils.join(options.getPreTriggerInclude(), ","); headers.put(HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, preTriggerInclude); } if (!Strings.isNullOrEmpty(options.getSessionToken())) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.getSessionToken()); } if (options.getResourceTokenExpirySeconds() != null) { headers.put(HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, String.valueOf(options.getResourceTokenExpirySeconds())); } if (options.getOfferThroughput() != null && options.getOfferThroughput() >= 0) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, options.getOfferThroughput().toString()); } else if (options.getOfferType() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } if (options.getOfferThroughput() == null) { if (options.getThroughputProperties() != null) { Offer offer = ModelBridgeInternal.getOfferFromThroughputProperties(options.getThroughputProperties()); final OfferAutoscaleSettings offerAutoscaleSettings = offer.getOfferAutoScaleSettings(); OfferAutoscaleAutoUpgradeProperties autoscaleAutoUpgradeProperties = null; if (offerAutoscaleSettings != null) { autoscaleAutoUpgradeProperties = offer.getOfferAutoScaleSettings().getAutoscaleAutoUpgradeProperties(); } if (offer.hasOfferThroughput() && (offerAutoscaleSettings != null && offerAutoscaleSettings.getMaxThroughput() >= 0 || autoscaleAutoUpgradeProperties != null && autoscaleAutoUpgradeProperties .getAutoscaleThroughputProperties() .getIncrementPercent() >= 0)) { throw new IllegalArgumentException("Autoscale provisioned throughput can not be configured with " + "fixed offer"); } if (offer.hasOfferThroughput()) { headers.put(HttpConstants.HttpHeaders.OFFER_THROUGHPUT, String.valueOf(offer.getThroughput())); } else if (offer.getOfferAutoScaleSettings() != null) { headers.put(HttpConstants.HttpHeaders.OFFER_AUTOPILOT_SETTINGS, ModelBridgeInternal.toJsonFromJsonSerializable(offer.getOfferAutoScaleSettings())); } } } if (options.isQuotaInfoEnabled()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } if (options.isScriptLoggingEnabled()) { headers.put(HttpConstants.HttpHeaders.SCRIPT_ENABLE_LOGGING, String.valueOf(true)); } if (options.getDedicatedGatewayRequestOptions() != null && options.getDedicatedGatewayRequestOptions().getMaxIntegratedCacheStaleness() != null) { headers.put(HttpConstants.HttpHeaders.DEDICATED_GATEWAY_PER_REQUEST_CACHE_STALENESS, String.valueOf(Utils.getMaxIntegratedCacheStalenessInMillis(options.getDedicatedGatewayRequestOptions()))); } return headers; } public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return this.resetSessionTokenRetryPolicy; } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Document document, RequestOptions options) { Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs .map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private Mono<RxDocumentServiceRequest> addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object document, RequestOptions options, Mono<Utils.ValueHolder<DocumentCollection>> collectionObs) { return collectionObs.map(collectionValueHolder -> { addPartitionKeyInformation(request, contentAsByteBuffer, document, options, collectionValueHolder.v); return request; }); } private void addPartitionKeyInformation(RxDocumentServiceRequest request, ByteBuffer contentAsByteBuffer, Object objectDoc, RequestOptions options, DocumentCollection collection) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.NONE)){ partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(options.getPartitionKey()); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { partitionKeyInternal = PartitionKeyInternal.getEmpty(); } else if (contentAsByteBuffer != null || objectDoc != null) { InternalObjectNode internalObjectNode; if (objectDoc instanceof InternalObjectNode) { internalObjectNode = (InternalObjectNode) objectDoc; } else if (objectDoc instanceof ObjectNode) { internalObjectNode = new InternalObjectNode((ObjectNode)objectDoc); } else if (contentAsByteBuffer != null) { contentAsByteBuffer.rewind(); internalObjectNode = new InternalObjectNode(contentAsByteBuffer); } else { throw new IllegalStateException("ContentAsByteBuffer and objectDoc are null"); } Instant serializationStartTime = Instant.now(); partitionKeyInternal = extractPartitionKeyValueFromDocument(internalObjectNode, partitionKeyDefinition); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTime, serializationEndTime, SerializationDiagnosticsContext.SerializationType.PARTITION_KEY_FETCH_SERIALIZATION ); SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } } else { throw new UnsupportedOperationException("PartitionKey value must be supplied for this operation."); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } public static PartitionKeyInternal extractPartitionKeyValueFromDocument( JsonSerializable document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { switch (partitionKeyDefinition.getKind()) { case HASH: String path = partitionKeyDefinition.getPaths().iterator().next(); List<String> parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, parts); if (value == null || value.getClass() == ObjectNode.class) { value = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } if (value instanceof PartitionKeyInternal) { return (PartitionKeyInternal) value; } else { return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); } } break; case MULTI_HASH: Object[] partitionKeyValues = new Object[partitionKeyDefinition.getPaths().size()]; for(int pathIter = 0 ; pathIter < partitionKeyDefinition.getPaths().size(); pathIter++){ String partitionPath = partitionKeyDefinition.getPaths().get(pathIter); List<String> partitionPathParts = PathParser.getPathParts(partitionPath); partitionKeyValues[pathIter] = ModelBridgeInternal.getObjectByPathFromJsonSerializable(document, partitionPathParts); } return PartitionKeyInternal.fromObjectArray(partitionKeyValues, false); default: throw new IllegalArgumentException("Unrecognized Partition kind: " + partitionKeyDefinition.getKind()); } } return null; } private Mono<RxDocumentServiceRequest> getCreateDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { throw new IllegalArgumentException("documentCollectionLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Instant serializationStartTimeUTC = Instant.now(); String trackingId = null; if (options != null) { trackingId = options.getTrackingId(); } ByteBuffer content = InternalObjectNode.serializeJsonToByteBuffer(document, mapper, trackingId); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Document, path, requestHeaders, options, content); if (operationType.isWriteOperation() && options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return addPartitionKeyInformation(request, content, document, options, collectionObs); } private Mono<RxDocumentServiceRequest> getBatchDocumentRequest(DocumentClientRetryPolicy requestRetryPolicy, String documentCollectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { checkArgument(StringUtils.isNotEmpty(documentCollectionLink), "expected non empty documentCollectionLink"); checkNotNull(serverBatchRequest, "expected non null serverBatchRequest"); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(Utils.getUTF8Bytes(serverBatchRequest.getRequestBody())); Instant serializationEndTimeUTC = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTimeUTC, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Batch); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Batch, ResourceType.Document, path, requestHeaders, options, content); if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); return collectionObs.map((Utils.ValueHolder<DocumentCollection> collectionValueHolder) -> { addBatchHeaders(request, serverBatchRequest, collectionValueHolder.v); return request; }); } private RxDocumentServiceRequest addBatchHeaders(RxDocumentServiceRequest request, ServerBatchRequest serverBatchRequest, DocumentCollection collection) { if(serverBatchRequest instanceof SinglePartitionKeyServerBatchRequest) { PartitionKey partitionKey = ((SinglePartitionKeyServerBatchRequest) serverBatchRequest).getPartitionKeyValue(); PartitionKeyInternal partitionKeyInternal; if (partitionKey.equals(PartitionKey.NONE)) { PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); partitionKeyInternal = ModelBridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else { partitionKeyInternal = BridgeInternal.getPartitionKeyInternal(partitionKey); } request.setPartitionKeyInternal(partitionKeyInternal); request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, Utils.escapeNonAscii(partitionKeyInternal.toJson())); } else if(serverBatchRequest instanceof PartitionKeyRangeServerBatchRequest) { request.setPartitionKeyRangeIdentity(new PartitionKeyRangeIdentity(((PartitionKeyRangeServerBatchRequest) serverBatchRequest).getPartitionKeyRangeId())); } else { throw new UnsupportedOperationException("Unknown Server request."); } request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_REQUEST, Boolean.TRUE.toString()); request.getHeaders().put(HttpConstants.HttpHeaders.IS_BATCH_ATOMIC, String.valueOf(serverBatchRequest.isAtomicBatch())); request.getHeaders().put(HttpConstants.HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR, String.valueOf(serverBatchRequest.isShouldContinueOnError())); request.setNumberOfItemsInBatchRequest(serverBatchRequest.getOperations().size()); return request; } /** * NOTE: Caller needs to consume it by subscribing to this Mono in order for the request to populate headers * @param request request to populate headers to * @param httpMethod http method * @return Mono, which on subscription will populate the headers in the request passed in the argument. */ private Mono<RxDocumentServiceRequest> populateHeadersAsync(RxDocumentServiceRequest request, RequestVerb httpMethod) { request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); if (this.masterKeyOrResourceToken != null || this.resourceTokensMap != null || this.cosmosAuthorizationTokenResolver != null || this.credential != null) { String resourceName = request.getResourceAddress(); String authorization = this.getUserAuthorizationToken( resourceName, request.getResourceType(), httpMethod, request.getHeaders(), AuthorizationTokenType.PrimaryMasterKey, request.properties); try { authorization = URLEncoder.encode(authorization, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode authtoken.", e); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); } if (this.apiType != null) { request.getHeaders().put(HttpConstants.HttpHeaders.API_TYPE, this.apiType.toString()); } this.populateCapabilitiesHeader(request); if ((RequestVerb.POST.equals(httpMethod) || RequestVerb.PUT.equals(httpMethod)) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON); } if (RequestVerb.PATCH.equals(httpMethod) && !request.getHeaders().containsKey(HttpConstants.HttpHeaders.CONTENT_TYPE)) { request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.JSON_PATCH); } if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.ACCEPT)) { request.getHeaders().put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } MetadataDiagnosticsContext metadataDiagnosticsCtx = BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics); if (this.requiresFeedRangeFiltering(request)) { return request.getFeedRange() .populateFeedRangeFilteringHeaders( this.getPartitionKeyRangeCache(), request, this.collectionCache.resolveCollectionAsync(metadataDiagnosticsCtx, request)) .flatMap(this::populateAuthorizationHeader); } return this.populateAuthorizationHeader(request); } private void populateCapabilitiesHeader(RxDocumentServiceRequest request) { if (!request.getHeaders().containsKey(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES)) { request .getHeaders() .put(HttpConstants.HttpHeaders.SDK_SUPPORTED_CAPABILITIES, HttpConstants.SDKSupportedCapabilities.SUPPORTED_CAPABILITIES); } } private boolean requiresFeedRangeFiltering(RxDocumentServiceRequest request) { if (request.getResourceType() != ResourceType.Document && request.getResourceType() != ResourceType.Conflict) { return false; } switch (request.getOperationType()) { case ReadFeed: case Query: case SqlQuery: return request.getFeedRange() != null; default: return false; } } @Override public Mono<RxDocumentServiceRequest> populateAuthorizationHeader(RxDocumentServiceRequest request) { if (request == null) { throw new IllegalArgumentException("request"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return request; }); } else { return Mono.just(request); } } @Override public Mono<HttpHeaders> populateAuthorizationHeader(HttpHeaders httpHeaders) { if (httpHeaders == null) { throw new IllegalArgumentException("httpHeaders"); } if (this.authorizationTokenType == AuthorizationTokenType.AadToken) { return AadTokenAuthorizationHelper.getAuthorizationToken(this.tokenCredentialCache) .map(authorization -> { httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorization); return httpHeaders; }); } return Mono.just(httpHeaders); } @Override public AuthorizationTokenType getAuthorizationTokenType() { return this.authorizationTokenType; } @Override public String getUserAuthorizationToken(String resourceName, ResourceType resourceType, RequestVerb requestVerb, Map<String, String> headers, AuthorizationTokenType tokenType, Map<String, Object> properties) { if (this.cosmosAuthorizationTokenResolver != null) { return this.cosmosAuthorizationTokenResolver.getAuthorizationToken(requestVerb.toUpperCase(), resourceName, this.resolveCosmosResourceType(resourceType).toString(), properties != null ? Collections.unmodifiableMap(properties) : null); } else if (credential != null) { return this.authorizationTokenProvider.generateKeyAuthorizationSignature(requestVerb, resourceName, resourceType, headers); } else if (masterKeyOrResourceToken != null && hasAuthKeyResourceToken && resourceTokensMap == null) { return masterKeyOrResourceToken; } else { assert resourceTokensMap != null; if(resourceType.equals(ResourceType.DatabaseAccount)) { return this.firstResourceTokenFromPermissionFeed; } return ResourceTokenAuthorizationHelper.getAuthorizationTokenUsingResourceTokens(resourceTokensMap, requestVerb, resourceName, headers); } } private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { CosmosResourceType cosmosResourceType = ModelBridgeInternal.fromServiceSerializedFormat(resourceType.toString()); if (cosmosResourceType == null) { return CosmosResourceType.SYSTEM; } return cosmosResourceType; } void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResponse response) { this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } private Mono<RxDocumentServiceResponse> create(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { RxStoreModel storeProxy = this.getStoreProxy(requestPopulated); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return storeProxy.processMessage(requestPopulated, operationContextAndListenerTuple); }); } private Mono<RxDocumentServiceResponse> upsert(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy, OperationContextAndListenerTuple operationContextAndListenerTuple) { return populateHeadersAsync(request, RequestVerb.POST) .flatMap(requestPopulated -> { Map<String, String> headers = requestPopulated.getHeaders(); assert (headers != null); headers.put(HttpConstants.HttpHeaders.IS_UPSERT, "true"); if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated, operationContextAndListenerTuple) .map(response -> { this.captureSessionToken(requestPopulated, response); return response; } ); }); } private Mono<RxDocumentServiceResponse> replace(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PUT) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } private Mono<RxDocumentServiceResponse> patch(RxDocumentServiceRequest request, DocumentClientRetryPolicy documentClientRetryPolicy) { return populateHeadersAsync(request, RequestVerb.PATCH) .flatMap(requestPopulated -> { if (documentClientRetryPolicy.getRetryContext() != null && documentClientRetryPolicy.getRetryContext().getRetryCount() > 0) { documentClientRetryPolicy.getRetryContext().updateEndTime(); } return getStoreProxy(requestPopulated).processMessage(requestPopulated); }); } @Override public Mono<ResourceResponse<Document>> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } private Mono<ResourceResponse<Document>> createDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> requestObs = getCreateDocumentRequest(requestRetryPolicy, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> { CosmosE2EOperationRetryPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(options); Mono<RxDocumentServiceResponse> rxDocumentServiceResponseMono = create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options)); return getRxDocumentServiceResponseMonoWithE2ETimeout(request, endToEndPolicyConfig, rxDocumentServiceResponseMono); }); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } private static <T> Mono<T> getRxDocumentServiceResponseMonoWithE2ETimeout(RxDocumentServiceRequest request, CosmosE2EOperationRetryPolicyConfig endToEndPolicyConfig, Mono<T> rxDocumentServiceResponseMono) { if (endToEndPolicyConfig != null && endToEndPolicyConfig.isEnabled()) { return rxDocumentServiceResponseMono .timeout(endToEndPolicyConfig.getEndToEndOperationTimeout()) .onErrorMap(throwable -> getCancellationException(request, throwable)); } return rxDocumentServiceResponseMono; } @Override public Mono<ResourceResponse<Document>> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRetryPolicyInstance = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), finalRetryPolicyInstance); } private Mono<ResourceResponse<Document>> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); Mono<RxDocumentServiceRequest> reqObs = getCreateDocumentRequest(retryPolicyInstance, collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Upsert); Mono<RxDocumentServiceResponse> responseObservable = reqObs.flatMap(request -> { CosmosE2EOperationRetryPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(options); return getRxDocumentServiceResponseMonoWithE2ETimeout(request, endToEndPolicyConfig, upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options))); }); return responseObservable .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(String documentLink, Object document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = Utils.getCollectionName(documentLink); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } if (document == null) { throw new IllegalArgumentException("document"); } Document typedDocument = documentFromObject(document, mapper); return this.replaceDocumentInternal(documentLink, typedDocument, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> replaceDocument(Document document, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.getSelfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } DocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> replaceDocumentInternal(Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { throw new IllegalArgumentException("document"); } return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); return Mono.error(e); } } private Mono<ResourceResponse<Document>> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { throw new IllegalArgumentException("document"); } logger.debug("Replacing a Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Replace); Instant serializationStartTimeUTC = Instant.now(); if (options != null) { String trackingId = options.getTrackingId(); if (trackingId != null && !trackingId.isEmpty()) { document.set(Constants.Properties.TRACKING_ID, trackingId); } } ByteBuffer content = serializeJsonToByteBuffer(document); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, content, document, options, collectionObs); return requestObs.flatMap(req -> { Mono<ResourceResponse<Document>> resourceResponseMono = replace(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class)); CosmosE2EOperationRetryPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(options); return getRxDocumentServiceResponseMonoWithE2ETimeout(request, endToEndPolicyConfig, resourceResponseMono); }); } private CosmosE2EOperationRetryPolicyConfig getEndToEndOperationLatencyPolicyConfig(RequestOptions options) { return (options != null && options.getCosmosEndToEndLatencyPolicyConfig() != null) ? options.getCosmosEndToEndLatencyPolicyConfig() : this.cosmosE2EOperationRetryPolicyConfig; } @Override public Mono<ResourceResponse<Document>> patchDocument(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> patchDocumentInternal(documentLink, cosmosPatchOperations, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Document>> patchDocumentInternal(String documentLink, CosmosPatchOperations cosmosPatchOperations, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { checkArgument(StringUtils.isNotEmpty(documentLink), "expected non empty documentLink"); checkNotNull(cosmosPatchOperations, "expected non null cosmosPatchOperations"); logger.debug("Running patch operations on Document. documentLink: [{}]", documentLink); final String path = Utils.joinPath(documentLink, null); final Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Document, OperationType.Patch); Instant serializationStartTimeUTC = Instant.now(); ByteBuffer content = ByteBuffer.wrap(PatchUtil.serializeCosmosPatchToByteArray(cosmosPatchOperations, options)); Instant serializationEndTime = Instant.now(); SerializationDiagnosticsContext.SerializationDiagnostics serializationDiagnostics = new SerializationDiagnosticsContext.SerializationDiagnostics( serializationStartTimeUTC, serializationEndTime, SerializationDiagnosticsContext.SerializationType.ITEM_SERIALIZATION); final RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Patch, ResourceType.Document, path, requestHeaders, options, content); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } SerializationDiagnosticsContext serializationDiagnosticsContext = BridgeInternal.getSerializationDiagnosticsContext(request.requestContext.cosmosDiagnostics); if (serializationDiagnosticsContext != null) { serializationDiagnosticsContext.addSerializationDiagnostics(serializationDiagnostics); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation( request, null, null, options, collectionObs); return requestObs.flatMap(req -> patch(request, retryPolicyInstance) .map(resp -> toResourceResponse(resp, Document.class))); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, null, options, requestRetryPolicy), requestRetryPolicy); } @Override public Mono<ResourceResponse<Document>> deleteDocument(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, internalObjectNode, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteDocumentInternal(String documentLink, InternalObjectNode internalObjectNode, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Deleting a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Document, path, requestHeaders, options); if (options != null && options.getNonIdempotentWriteRetriesEnabled()) { request.setNonIdempotentWriteRetriesEnabled(true); } if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, internalObjectNode, options, collectionObs); return requestObs.flatMap(req -> this .delete(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKey(String collectionLink, PartitionKey partitionKey, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAllDocumentsByPartitionKeyInternal(collectionLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<Document>> deleteAllDocumentsByPartitionKeyInternal(String collectionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } logger.debug("Deleting all items by Partition Key. collectionLink: [{}]", collectionLink); String path = Utils.joinPath(collectionLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.PartitionKey, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.PartitionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); return requestObs.flatMap(req -> this .deleteAllItemsByPartitionKey(req, retryPolicyInstance, getOperationContextAndListenerTuple(options)) .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class))); } catch (Exception e) { logger.debug("Failure in deleting documents due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public Mono<ResourceResponse<Document>> readDocument(String documentLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Document>> readDocumentInternal(String documentLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { throw new IllegalArgumentException("documentLink"); } logger.debug("Reading a Document. documentLink: [{}]", documentLink); String path = Utils.joinPath(documentLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.Document, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Document, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = this.collectionCache.resolveCollectionAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), request); Mono<RxDocumentServiceRequest> requestObs = addPartitionKeyInformation(request, null, null, options, collectionObs); CosmosE2EOperationRetryPolicyConfig endToEndPolicyConfig = getEndToEndOperationLatencyPolicyConfig(options); return requestObs.flatMap(req -> { Mono<ResourceResponse<Document>> resourceResponseMono = this.read(request, retryPolicyInstance).map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); return getRxDocumentServiceResponseMonoWithE2ETimeout(request, endToEndPolicyConfig, resourceResponseMono); }); } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); return Mono.error(e); } } @Override public <T> Flux<FeedResponse<T>> readDocuments( String collectionLink, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return queryDocuments(collectionLink, "SELECT * FROM r", options, classOfT); } @Override public <T> Mono<FeedResponse<T>> readMany( List<CosmosItemIdentity> itemIdentityList, String collectionLink, CosmosQueryRequestOptions options, Class<T> klass) { String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs .flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } final PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); Mono<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = partitionKeyRangeCache .tryLookupAsync(BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap = new HashMap<>(); CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } itemIdentityList .forEach(itemIdentity -> { if (pkDefinition.getKind().equals(PartitionKind.MULTI_HASH) && ModelBridgeInternal.getPartitionKeyInternal(itemIdentity.getPartitionKey()) .getComponents().size() != pkDefinition.getPaths().size()) { throw new IllegalArgumentException(RMResources.PartitionKeyMismatch); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal( itemIdentity.getPartitionKey()), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); if (partitionRangeItemKeyMap.get(range) == null) { List<CosmosItemIdentity> list = new ArrayList<>(); list.add(itemIdentity); partitionRangeItemKeyMap.put(range, list); } else { List<CosmosItemIdentity> pairs = partitionRangeItemKeyMap.get(range); pairs.add(itemIdentity); partitionRangeItemKeyMap.put(range, pairs); } }); Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = getRangeQueryMap(partitionRangeItemKeyMap, collection.getPartitionKey()); Flux<FeedResponse<Document>> pointReads = createPointReadOperations( partitionRangeItemKeyMap, resourceLink, options, klass); Flux<FeedResponse<Document>> queries = createReadManyQuery( resourceLink, new SqlQuerySpec(DUMMY_SQL_QUERY), options, Document.class, ResourceType.Document, collection, Collections.unmodifiableMap(rangeQueryMap)); return Flux.merge(pointReads, queries) .collectList() .map(feedList -> { List<T> finalList = new ArrayList<>(); HashMap<String, String> headers = new HashMap<>(); ConcurrentMap<String, QueryMetrics> aggregatedQueryMetrics = new ConcurrentHashMap<>(); Collection<ClientSideRequestStatistics> aggregateRequestStatistics = new DistinctClientSideRequestStatisticsCollection(); double requestCharge = 0; for (FeedResponse<Document> page : feedList) { ConcurrentMap<String, QueryMetrics> pageQueryMetrics = ModelBridgeInternal.queryMetrics(page); if (pageQueryMetrics != null) { pageQueryMetrics.forEach( aggregatedQueryMetrics::putIfAbsent); } requestCharge += page.getRequestCharge(); finalList.addAll(page.getResults().stream().map(document -> ModelBridgeInternal.toObjectFromJsonSerializable(document, klass)).collect(Collectors.toList())); aggregateRequestStatistics.addAll(diagnosticsAccessor.getClientSideRequestStatistics(page.getCosmosDiagnostics())); } CosmosDiagnostics aggregatedDiagnostics = BridgeInternal.createCosmosDiagnostics(aggregatedQueryMetrics); diagnosticsAccessor.addClientSideDiagnosticsToFeed( aggregatedDiagnostics, aggregateRequestStatistics); headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double .toString(requestCharge)); FeedResponse<T> frp = BridgeInternal .createFeedResponseWithQueryMetrics( finalList, headers, aggregatedQueryMetrics, null, false, false, aggregatedDiagnostics); return frp; }); }); } ); } private Map<PartitionKeyRange, SqlQuerySpec> getRangeQueryMap( Map<PartitionKeyRange, List<CosmosItemIdentity>> partitionRangeItemKeyMap, PartitionKeyDefinition partitionKeyDefinition) { Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap = new HashMap<>(); String partitionKeySelector = createPkSelector(partitionKeyDefinition); for(Map.Entry<PartitionKeyRange, List<CosmosItemIdentity>> entry: partitionRangeItemKeyMap.entrySet()) { SqlQuerySpec sqlQuerySpec; List<CosmosItemIdentity> cosmosItemIdentityList = entry.getValue(); if (cosmosItemIdentityList.size() > 1) { if (partitionKeySelector.equals("[\"id\"]")) { sqlQuerySpec = createReadManyQuerySpecPartitionKeyIdSame(cosmosItemIdentityList, partitionKeySelector); } else if (partitionKeyDefinition.getKind().equals(PartitionKind.MULTI_HASH)) { sqlQuerySpec = createReadManyQuerySpecMultiHash(entry.getValue(), partitionKeyDefinition); } else { sqlQuerySpec = createReadManyQuerySpec(cosmosItemIdentityList, partitionKeySelector); } rangeQueryMap.put(entry.getKey(), sqlQuerySpec); } } return rangeQueryMap; } private SqlQuerySpec createReadManyQuerySpecPartitionKeyIdSame( List<CosmosItemIdentity> idPartitionKeyPairList, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE c.id IN ( "); for (int i = 0; i < idPartitionKeyPairList.size(); i++) { CosmosItemIdentity itemIdentity = idPartitionKeyPairList.get(i); String idValue = itemIdentity.getId(); String idParamName = "@param" + i; PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); if (!Objects.equals(idValue, pkValue)) { continue; } parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append(idParamName); if (i < idPartitionKeyPairList.size() - 1) { queryStringBuilder.append(", "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpec(List<CosmosItemIdentity> itemIdentities, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkParamName = "@param" + (2 * i); parameters.add(new SqlParameter(pkParamName, pkValue)); String idValue = itemIdentity.getId(); String idParamName = "@param" + (2 * i + 1); parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); queryStringBuilder.append(" AND "); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private SqlQuerySpec createReadManyQuerySpecMultiHash( List<CosmosItemIdentity> itemIdentities, PartitionKeyDefinition partitionKeyDefinition) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE ( "); int paramCount = 0; for (int i = 0; i < itemIdentities.size(); i++) { CosmosItemIdentity itemIdentity = itemIdentities.get(i); PartitionKey pkValueAsPartitionKey = itemIdentity.getPartitionKey(); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(pkValueAsPartitionKey); String pkValueString = (String) pkValue; List<List<String>> partitionKeyParams = new ArrayList<>(); List<String> paths = partitionKeyDefinition.getPaths(); int pathCount = 0; for (String subPartitionKey: pkValueString.split("=")) { String pkParamName = "@param" + paramCount; partitionKeyParams.add(Arrays.asList(paths.get(pathCount), pkParamName)); parameters.add(new SqlParameter(pkParamName, subPartitionKey)); paramCount++; pathCount++; } String idValue = itemIdentity.getId(); String idParamName = "@param" + paramCount; paramCount++; parameters.add(new SqlParameter(idParamName, idValue)); queryStringBuilder.append("("); queryStringBuilder.append("c.id = "); queryStringBuilder.append(idParamName); for (List<String> pkParam: partitionKeyParams) { queryStringBuilder.append(" AND "); queryStringBuilder.append(" c."); queryStringBuilder.append(pkParam.get(0).substring(1)); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParam.get(1)); } queryStringBuilder.append(" )"); if (i < itemIdentities.size() - 1) { queryStringBuilder.append(" OR "); } } queryStringBuilder.append(" )"); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } private String createPkSelector(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getPaths() .stream() .map(pathPart -> StringUtils.substring(pathPart, 1)) .map(pathPart -> StringUtils.replace(pathPart, "\"", "\\")) .map(part -> "[\"" + part + "\"]") .collect(Collectors.joining()); } private <T extends Resource> Flux<FeedResponse<T>> createReadManyQuery( String parentResourceLink, SqlQuerySpec sqlQuery, CosmosQueryRequestOptions options, Class<T> klass, ResourceType resourceTypeEnum, DocumentCollection collection, Map<PartitionKeyRange, SqlQuerySpec> rangeQueryMap) { if (rangeQueryMap.isEmpty()) { return Flux.empty(); } UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); Flux<? extends IDocumentQueryExecutionContext<T>> executionContext = DocumentQueryExecutionContextFactory.createReadManyQueryAsync(this, queryClient, collection.getResourceId(), sqlQuery, rangeQueryMap, options, collection.getResourceId(), parentResourceLink, activityId, klass, resourceTypeEnum); return executionContext.flatMap(IDocumentQueryExecutionContext<T>::executeAsync); } private <T> Flux<FeedResponse<Document>> createPointReadOperations( Map<PartitionKeyRange, List<CosmosItemIdentity>> singleItemPartitionRequestMap, String resourceLink, CosmosQueryRequestOptions queryRequestOptions, Class<T> klass ) { return Flux.fromIterable(singleItemPartitionRequestMap.values()) .flatMap(cosmosItemIdentityList -> { if (cosmosItemIdentityList.size() == 1) { CosmosItemIdentity firstIdentity = cosmosItemIdentityList.get(0); RequestOptions requestOptions = ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .toRequestOptions(queryRequestOptions); requestOptions.setPartitionKey(firstIdentity.getPartitionKey()); return this.readDocument((resourceLink + firstIdentity.getId()), requestOptions); } return Mono.empty(); }) .flatMap(resourceResponse -> { CosmosItemResponse<T> cosmosItemResponse = ModelBridgeInternal.createCosmosAsyncItemResponse(resourceResponse, klass, getItemDeserializer()); FeedResponse<Document> feedResponse = ModelBridgeInternal.createFeedResponse( Arrays.asList(InternalObjectNode.fromObject(cosmosItemResponse.getItem())), cosmosItemResponse.getResponseHeaders()); diagnosticsAccessor.addClientSideDiagnosticsToFeed( feedResponse.getCosmosDiagnostics(), Collections.singleton( BridgeInternal.getClientSideRequestStatics(cosmosItemResponse.getDiagnostics()))); return Mono.just(feedResponse); }); } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, String query, CosmosQueryRequestOptions options, Class<T> classOfT) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options, classOfT); } private IDocumentQueryClient documentQueryClientImpl(RxDocumentClientImpl rxDocumentClientImpl, OperationContextAndListenerTuple operationContextAndListenerTuple) { return new IDocumentQueryClient () { @Override public RxCollectionCache getCollectionCache() { return RxDocumentClientImpl.this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return RxDocumentClientImpl.this.partitionKeyRangeCache; } @Override public IRetryPolicyFactory getResetSessionTokenRetryPolicy() { return RxDocumentClientImpl.this.resetSessionTokenRetryPolicy; } @Override public ConsistencyLevel getDefaultConsistencyLevelAsync() { return RxDocumentClientImpl.this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } @Override public ConsistencyLevel getDesiredConsistencyLevelAsync() { return RxDocumentClientImpl.this.consistencyLevel; } @Override public Mono<RxDocumentServiceResponse> executeQueryAsync(RxDocumentServiceRequest request) { if (operationContextAndListenerTuple == null) { return RxDocumentClientImpl.this.query(request).single(); } else { final OperationListener listener = operationContextAndListenerTuple.getOperationListener(); final OperationContext operationContext = operationContextAndListenerTuple.getOperationContext(); request.getHeaders().put(HttpConstants.HttpHeaders.CORRELATED_ACTIVITY_ID, operationContext.getCorrelationActivityId()); listener.requestListener(operationContext, request); return RxDocumentClientImpl.this.query(request).single().doOnNext( response -> listener.responseListener(operationContext, response) ).doOnError( ex -> listener.exceptionListener(operationContext, ex) ); } } @Override public QueryCompatibilityMode getQueryCompatibilityMode() { return QueryCompatibilityMode.Default; } @Override public Mono<RxDocumentServiceResponse> readFeedAsync(RxDocumentServiceRequest request) { return null; } }; } @Override public <T> Flux<FeedResponse<T>> queryDocuments( String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options, Class<T> classOfT) { SqlQuerySpecLogger.getInstance().logQuery(querySpec); return createQuery(collectionLink, querySpec, options, classOfT, ResourceType.Document); } @Override public <T> Flux<FeedResponse<T>> queryDocumentChangeFeed( final DocumentCollection collection, final CosmosChangeFeedRequestOptions changeFeedOptions, Class<T> classOfT) { checkNotNull(collection, "Argument 'collection' must not be null."); ChangeFeedQueryImpl<T> changeFeedQueryImpl = new ChangeFeedQueryImpl<>( this, ResourceType.Document, classOfT, collection.getAltLink(), collection.getResourceId(), changeFeedOptions); return changeFeedQueryImpl.executeAsync(); } @Override public <T> Flux<FeedResponse<T>> readAllDocuments( String collectionLink, PartitionKey partitionKey, CosmosQueryRequestOptions options, Class<T> classOfT) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (partitionKey == null) { throw new IllegalArgumentException("partitionKey"); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Query, ResourceType.Document, collectionLink, null ); Flux<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request).flux(); return collectionObs.flatMap(documentCollectionResourceResponse -> { DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } PartitionKeyDefinition pkDefinition = collection.getPartitionKey(); String pkSelector = createPkSelector(pkDefinition); SqlQuerySpec querySpec = createLogicalPartitionScanQuerySpec(partitionKey, pkSelector); String resourceLink = parentResourceLinkToQueryLink(collectionLink, ResourceType.Document); UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = documentQueryClientImpl(RxDocumentClientImpl.this, getOperationContextAndListenerTuple(options)); final CosmosQueryRequestOptions effectiveOptions = ModelBridgeInternal.createQueryRequestOptions(options); InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, resourceLink, ModelBridgeInternal.getPropertiesFromQueryRequestOptions(effectiveOptions)); return ObservableHelper.fluxInlineIfPossibleAsObs( () -> { Flux<Utils.ValueHolder<CollectionRoutingMap>> valueHolderMono = this.partitionKeyRangeCache .tryLookupAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), null, null).flux(); return valueHolderMono.flatMap(collectionRoutingMapValueHolder -> { CollectionRoutingMap routingMap = collectionRoutingMapValueHolder.v; if (routingMap == null) { return Mono.error(new IllegalStateException("Failed to get routing map.")); } String effectivePartitionKeyString = PartitionKeyInternalHelper .getEffectivePartitionKeyString( BridgeInternal.getPartitionKeyInternal(partitionKey), pkDefinition); PartitionKeyRange range = routingMap.getRangeByEffectivePartitionKey(effectivePartitionKeyString); return createQueryInternal( resourceLink, querySpec, ModelBridgeInternal.setPartitionKeyRangeIdInternal(effectiveOptions, range.getId()), classOfT, ResourceType.Document, queryClient, activityId); }); }, invalidPartitionExceptionRetryPolicy); }); } @Override public Map<String, PartitionedQueryExecutionInfo> getQueryPlanCache() { return queryPlanCache; } @Override public Flux<FeedResponse<PartitionKeyRange>> readPartitionKeyRanges(final String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.PartitionKeyRange, PartitionKeyRange.class, Utils.joinPath(collectionLink, Paths.PARTITION_KEY_RANGES_PATH_SEGMENT)); } private RxDocumentServiceRequest getStoredProcedureRequest(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } validateResource(storedProcedure); String path = Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); return request; } private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collectionLink, UserDefinedFunction udf, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (udf == null) { throw new IllegalArgumentException("udf"); } validateResource(udf); String path = Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<StoredProcedure>> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", collectionLink, storedProcedure.getId()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); RxDocumentClientImpl.validateResource(storedProcedure); String path = Utils.joinPath(storedProcedure.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } private Mono<ResourceResponse<StoredProcedure>> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Deleting a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<StoredProcedure>> readStoredProcedure(String storedProcedureLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<StoredProcedure>> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(storedProcedureLink)) { throw new IllegalArgumentException("storedProcedureLink"); } logger.debug("Reading a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.StoredProcedure, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, StoredProcedure.class)); } catch (Exception e) { logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<StoredProcedure>> readStoredProcedures(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.StoredProcedure, StoredProcedure.class, Utils.joinPath(collectionLink, Paths.STORED_PROCEDURES_PATH_SEGMENT)); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<StoredProcedure>> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override public Mono<StoredProcedureResponse> executeStoredProcedure(String storedProcedureLink, RequestOptions options, List<Object> procedureParams) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams, documentClientRetryPolicy), documentClientRetryPolicy); } @Override public Mono<CosmosBatchResponse> executeBatchRequest(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, boolean disableAutomaticIdGeneration) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> executeBatchRequestInternal(collectionLink, serverBatchRequest, options, documentClientRetryPolicy, disableAutomaticIdGeneration), documentClientRetryPolicy); } private Mono<StoredProcedureResponse> executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, List<Object> procedureParams, DocumentClientRetryPolicy retryPolicy) { try { logger.debug("Executing a StoredProcedure. storedProcedureLink [{}]", storedProcedureLink); String path = Utils.joinPath(storedProcedureLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.StoredProcedure, OperationType.ExecuteJavaScript); requestHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ExecuteJavaScript, ResourceType.StoredProcedure, path, procedureParams != null && !procedureParams.isEmpty() ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); if (retryPolicy != null) { retryPolicy.onBeforeSendRequest(request); } Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> create(request, retryPolicy, getOperationContextAndListenerTuple(options)) .map(response -> { this.captureSessionToken(request, response); return toStoredProcedureResponse(response); })); } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); return Mono.error(e); } } private Mono<CosmosBatchResponse> executeBatchRequestInternal(String collectionLink, ServerBatchRequest serverBatchRequest, RequestOptions options, DocumentClientRetryPolicy requestRetryPolicy, boolean disableAutomaticIdGeneration) { try { logger.debug("Executing a Batch request with number of operations {}", serverBatchRequest.getOperations().size()); Mono<RxDocumentServiceRequest> requestObs = getBatchDocumentRequest(requestRetryPolicy, collectionLink, serverBatchRequest, options, disableAutomaticIdGeneration); Mono<RxDocumentServiceResponse> responseObservable = requestObs.flatMap(request -> create(request, requestRetryPolicy, getOperationContextAndListenerTuple(options))); return responseObservable .map(serviceResponse -> BatchResponseParser.fromDocumentServiceResponse(serviceResponse, serverBatchRequest, true)); } catch (Exception ex) { logger.debug("Failure in executing a batch due to [{}]", ex.getMessage(), ex); return Mono.error(ex); } } @Override public Mono<ResourceResponse<Trigger>> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, trigger.getId()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigger trigger, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } if (trigger == null) { throw new IllegalArgumentException("trigger"); } RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Trigger, path, trigger, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Trigger>> replaceTrigger(Trigger trigger, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> replaceTriggerInternal(Trigger trigger, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (trigger == null) { throw new IllegalArgumentException("trigger"); } logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); RxDocumentClientImpl.validateResource(trigger); String path = Utils.joinPath(trigger.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> deleteTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> deleteTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Deleting a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Trigger>> readTrigger(String triggerLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Trigger>> readTriggerInternal(String triggerLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); } logger.debug("Reading a Trigger. triggerLink [{}]", triggerLink); String path = Utils.joinPath(triggerLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Trigger, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Trigger, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Trigger.class)); } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Trigger>> readTriggers(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Trigger, Trigger.class, Utils.joinPath(collectionLink, Paths.TRIGGERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Trigger>> queryTriggers(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override public Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, udf.getId()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.create(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (udf == null) { throw new IllegalArgumentException("udf"); } logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); validateResource(udf); String path = Utils.joinPath(udf.getSelfLink(), null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Deleting a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null){ retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunction(String udfLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<UserDefinedFunction>> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(udfLink)) { throw new IllegalArgumentException("udfLink"); } logger.debug("Reading a UserDefinedFunction. udfLink [{}]", udfLink); String path = Utils.joinPath(udfLink, null); Map<String, String> requestHeaders = this.getRequestHeaders(options, ResourceType.UserDefinedFunction, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.UserDefinedFunction, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, UserDefinedFunction.class)); } catch (Exception e) { logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<UserDefinedFunction>> readUserDefinedFunctions(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.UserDefinedFunction, UserDefinedFunction.class, Utils.joinPath(collectionLink, Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<UserDefinedFunction>> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override public Mono<ResourceResponse<Conflict>> readConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> readConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Reading a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Conflict>> readConflicts(String collectionLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } return readFeed(options, ResourceType.Conflict, Conflict.class, Utils.joinPath(collectionLink, Paths.CONFLICTS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, String query, CosmosQueryRequestOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Conflict>> queryConflicts(String collectionLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override public Mono<ResourceResponse<Conflict>> deleteConflict(String conflictLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Conflict>> deleteConflictInternal(String conflictLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { throw new IllegalArgumentException("conflictLink"); } logger.debug("Deleting a Conflict. conflictLink [{}]", conflictLink); String path = Utils.joinPath(conflictLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Conflict, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); Mono<RxDocumentServiceRequest> reqObs = addPartitionKeyInformation(request, null, null, options); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Conflict.class)); }); } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> createUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<User>> createUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> upsertUser(String databaseLink, User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> upsertUserInternal(String databaseLink, User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (user == null) { throw new IllegalArgumentException("user"); } RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.User, path, user, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<User>> replaceUser(User user, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> replaceUserInternal(User user, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); } logger.debug("Replacing a User. user id [{}]", user.getId()); RxDocumentClientImpl.validateResource(user); String path = Utils.joinPath(user.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Mono<ResourceResponse<User>> deleteUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> deleteUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Deleting a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<User>> readUser(String userLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<User>> readUserInternal(String userLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } logger.debug("Reading a User. userLink [{}]", userLink); String path = Utils.joinPath(userLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.User, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.User, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, User.class)); } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<User>> readUsers(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.User, User.class, Utils.joinPath(databaseLink, Paths.USERS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, String query, CosmosQueryRequestOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<User>> queryUsers(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override public Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKey(String clientEncryptionKeyLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readClientEncryptionKeyInternal(clientEncryptionKeyLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> readClientEncryptionKeyInternal(String clientEncryptionKeyLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(clientEncryptionKeyLink)) { throw new IllegalArgumentException("clientEncryptionKeyLink"); } logger.debug("Reading a client encryption key. clientEncryptionKeyLink [{}]", clientEncryptionKeyLink); String path = Utils.joinPath(clientEncryptionKeyLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.ClientEncryptionKey, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in reading a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKey(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createClientEncryptionKeyInternal(databaseLink, clientEncryptionKey, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> createClientEncryptionKeyInternal(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a client encryption key. databaseLink [{}], clientEncryptionKey id [{}]", databaseLink, clientEncryptionKey.getId()); RxDocumentServiceRequest request = getClientEncryptionKeyRequest(databaseLink, clientEncryptionKey, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in creating a client encryption key due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getClientEncryptionKeyRequest(String databaseLink, ClientEncryptionKey clientEncryptionKey, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKey(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceClientEncryptionKeyInternal(clientEncryptionKey, nameBasedLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<ClientEncryptionKey>> replaceClientEncryptionKeyInternal(ClientEncryptionKey clientEncryptionKey, String nameBasedLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (clientEncryptionKey == null) { throw new IllegalArgumentException("clientEncryptionKey"); } logger.debug("Replacing a clientEncryptionKey. clientEncryptionKey id [{}]", clientEncryptionKey.getId()); RxDocumentClientImpl.validateResource(clientEncryptionKey); String path = Utils.joinPath(nameBasedLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.ClientEncryptionKey, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.ClientEncryptionKey, path, clientEncryptionKey, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, ClientEncryptionKey.class)); } catch (Exception e) { logger.debug("Failure in replacing a clientEncryptionKey due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<ClientEncryptionKey>> readClientEncryptionKeys(String databaseLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); } return readFeed(options, ResourceType.ClientEncryptionKey, ClientEncryptionKey.class, Utils.joinPath(databaseLink, Paths.CLIENT_ENCRYPTION_KEY_PATH_SEGMENT)); } @Override public Flux<FeedResponse<ClientEncryptionKey>> queryClientEncryptionKeys(String databaseLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(databaseLink, querySpec, options, ClientEncryptionKey.class, ResourceType.ClientEncryptionKey); } @Override public Mono<ResourceResponse<Permission>> createPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options, documentClientRetryPolicy), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } private Mono<ResourceResponse<Permission>> createPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request, documentClientRetryPolicy, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> upsertPermission(String userLink, Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.upsert(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } private RxDocumentServiceRequest getPermissionRequest(String userLink, Permission permission, RequestOptions options, OperationType operationType) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } if (permission == null) { throw new IllegalArgumentException("permission"); } RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, operationType); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, operationType, ResourceType.Permission, path, permission, requestHeaders, options); return request; } @Override public Mono<ResourceResponse<Permission>> replacePermission(Permission permission, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> replacePermissionInternal(Permission permission, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); } logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); RxDocumentClientImpl.validateResource(permission); String path = Utils.joinPath(permission.getSelfLink(), null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Replace); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.replace(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> deletePermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> deletePermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Deleting a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Delete); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Delete, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.delete(request, retryPolicyInstance, getOperationContextAndListenerTuple(options)).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Permission>> readPermission(String permissionLink, RequestOptions options) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Permission>> readPermissionInternal(String permissionLink, RequestOptions options, DocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); } logger.debug("Reading a Permission. permissionLink [{}]", permissionLink); String path = Utils.joinPath(permissionLink, null); Map<String, String> requestHeaders = getRequestHeaders(options, ResourceType.Permission, OperationType.Read); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Permission, path, requestHeaders, options); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Permission.class)); } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Permission>> readPermissions(String userLink, CosmosQueryRequestOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); } return readFeed(options, ResourceType.Permission, Permission.class, Utils.joinPath(userLink, Paths.PERMISSIONS_PATH_SEGMENT)); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, String query, CosmosQueryRequestOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Permission>> queryPermissions(String userLink, SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override public Mono<ResourceResponse<Offer>> replaceOffer(Offer offer) { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer, documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<ResourceResponse<Offer>> replaceOfferInternal(Offer offer, DocumentClientRetryPolicy documentClientRetryPolicy) { try { if (offer == null) { throw new IllegalArgumentException("offer"); } logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); RxDocumentClientImpl.validateResource(offer); String path = Utils.joinPath(offer.getSelfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request, documentClientRetryPolicy).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Mono<ResourceResponse<Offer>> readOffer(String offerLink) { DocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } private Mono<ResourceResponse<Offer>> readOfferInternal(String offerLink, DocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); } logger.debug("Reading an Offer. offerLink [{}]", offerLink); String path = Utils.joinPath(offerLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.Offer, path, (HashMap<String, String>)null, null); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } return this.read(request, retryPolicyInstance).map(response -> toResourceResponse(response, Offer.class)); } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); return Mono.error(e); } } @Override public Flux<FeedResponse<Offer>> readOffers(CosmosQueryRequestOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } private <T> Flux<FeedResponse<T>> readFeed( CosmosQueryRequestOptions options, ResourceType resourceType, Class<T> klass, String resourceLink) { if (options == null) { options = new CosmosQueryRequestOptions(); } Integer maxItemCount = ModelBridgeInternal.getMaxItemCountFromQueryRequestOptions(options); int maxPageSize = maxItemCount != null ? maxItemCount : -1; final CosmosQueryRequestOptions finalCosmosQueryRequestOptions = options; DocumentClientRetryPolicy retryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); BiFunction<String, Integer, RxDocumentServiceRequest> createRequestFunc = (continuationToken, pageSize) -> { Map<String, String> requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); } requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Integer.toString(pageSize)); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.ReadFeed, resourceType, resourceLink, requestHeaders, finalCosmosQueryRequestOptions); retryPolicy.onBeforeSendRequest(request); return request; }; Function<RxDocumentServiceRequest, Mono<FeedResponse<T>>> executeFunc = request -> ObservableHelper .inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage( response, ImplementationBridgeHelpers .CosmosQueryRequestOptionsHelper .getCosmosQueryRequestOptionsAccessor() .getItemFactoryMethod(finalCosmosQueryRequestOptions, klass), klass)), retryPolicy); return Paginator.getPaginatedQueryResultAsObservable( options, createRequestFunc, executeFunc, maxPageSize); } @Override public Flux<FeedResponse<Offer>> queryOffers(String query, CosmosQueryRequestOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override public Flux<FeedResponse<Offer>> queryOffers(SqlQuerySpec querySpec, CosmosQueryRequestOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override public Mono<DatabaseAccount> getDatabaseAccount() { DocumentClientRetryPolicy documentClientRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(documentClientRetryPolicy), documentClientRetryPolicy); } private Mono<DatabaseAccount> getDatabaseAccountInternal(DocumentClientRetryPolicy documentClientRetryPolicy) { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", (HashMap<String, String>) null, null); return this.read(request, documentClientRetryPolicy).map(ModelBridgeInternal::toDatabaseAccount); } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); return Mono.error(e); } } public Object getSession() { return this.sessionContainer; } public void setSession(Object sessionContainer) { this.sessionContainer = (SessionContainer) sessionContainer; } @Override public RxClientCollectionCache getCollectionCache() { return this.collectionCache; } @Override public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } @Override public GlobalEndpointManager getGlobalEndpointManager() { return this.globalEndpointManager; } @Override public AddressSelector getAddressSelector() { return new AddressSelector(this.addressResolver, this.configs.getProtocol()); } public Flux<DatabaseAccount> getDatabaseAccountFromEndpoint(URI endpoint) { return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(this, OperationType.Read, ResourceType.DatabaseAccount, "", null, (Object) null); return this.populateHeadersAsync(request, RequestVerb.GET) .flatMap(requestPopulated -> { requestPopulated.setEndpointOverride(endpoint); return this.gatewayProxy.processMessage(requestPopulated).doOnError(e -> { String message = String.format("Failed to retrieve database account information. %s", e.getCause() != null ? e.getCause().toString() : e.toString()); logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> this.useMultipleWriteLocations = this.connectionPolicy.isMultipleWriteRegionsEnabled() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount)); }); }); } /** * Certain requests must be routed through gateway even when the client connectivity mode is direct. * * @param request * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { if (request.useGatewayMode) { return this.gatewayProxy; } ResourceType resourceType = request.getResourceType(); OperationType operationType = request.getOperationType(); if (resourceType == ResourceType.Offer || resourceType == ResourceType.ClientEncryptionKey || resourceType.isScript() && operationType != OperationType.ExecuteJavaScript || resourceType == ResourceType.PartitionKeyRange || resourceType == ResourceType.PartitionKey && operationType == OperationType.Delete) { return this.gatewayProxy; } if (operationType == OperationType.Create || operationType == OperationType.Upsert) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection || resourceType == ResourceType.Permission) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Delete) { if (resourceType == ResourceType.Database || resourceType == ResourceType.User || resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Replace) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else if (operationType == OperationType.Read) { if (resourceType == ResourceType.DocumentCollection) { return this.gatewayProxy; } else { return this.storeModel; } } else { if ((operationType == OperationType.Query || operationType == OperationType.SqlQuery || operationType == OperationType.ReadFeed) && Utils.isCollectionChild(request.getResourceType())) { if (request.getPartitionKeyRangeIdentity() == null && request.getHeaders().get(HttpConstants.HttpHeaders.PARTITION_KEY) == null) { return this.gatewayProxy; } } return this.storeModel; } } @Override public void close() { logger.info("Attempting to close client {}", this.clientId); if (!closed.getAndSet(true)) { activeClientsCnt.decrementAndGet(); logger.info("Shutting down ..."); logger.info("Closing Global Endpoint Manager ..."); LifeCycleUtils.closeQuietly(this.globalEndpointManager); logger.info("Closing StoreClientFactory ..."); LifeCycleUtils.closeQuietly(this.storeClientFactory); logger.info("Shutting down reactorHttpClient ..."); LifeCycleUtils.closeQuietly(this.reactorHttpClient); logger.info("Shutting down CpuMonitor ..."); CpuMemoryMonitor.unregister(this); if (this.throughputControlEnabled.get()) { logger.info("Closing ThroughputControlStore ..."); this.throughputControlStore.close(); } logger.info("Shutting down completed."); } else { logger.warn("Already shutdown!"); } } @Override public ItemDeserializer getItemDeserializer() { return this.itemDeserializer; } @Override public synchronized void enableThroughputControlGroup(ThroughputControlGroupInternal group, Mono<Integer> throughputQueryMono) { checkNotNull(group, "Throughput control group can not be null"); if (this.throughputControlEnabled.compareAndSet(false, true)) { this.throughputControlStore = new ThroughputControlStore( this.collectionCache, this.connectionPolicy.getConnectionMode(), this.partitionKeyRangeCache); this.storeModel.enableThroughputControl(throughputControlStore); } this.throughputControlStore.enableThroughputControlGroup(group, throughputQueryMono); } @Override public Flux<Void> submitOpenConnectionTasksAndInitCaches(CosmosContainerProactiveInitConfig proactiveContainerInitConfig) { return this.storeModel.submitOpenConnectionTasksAndInitCaches(proactiveContainerInitConfig); } @Override public ConsistencyLevel getDefaultConsistencyLevelOfAccount() { return this.gatewayConfigurationReader.getDefaultConsistencyLevel(); } /*** * Configure fault injector provider. * * @param injectorProvider the fault injector provider. */ @Override public void configureFaultInjectorProvider(IFaultInjectorProvider injectorProvider) { checkNotNull(injectorProvider, "Argument 'injectorProvider' can not be null"); if (this.connectionPolicy.getConnectionMode() == ConnectionMode.DIRECT) { this.storeModel.configureFaultInjectorProvider(injectorProvider); } else { throw new IllegalArgumentException("configureFaultInjectorProvider is not supported for gateway mode"); } } @Override public void recordOpenConnectionsAndInitCachesCompleted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesCompleted(cosmosContainerIdentities); } @Override public void recordOpenConnectionsAndInitCachesStarted(List<CosmosContainerIdentity> cosmosContainerIdentities) { this.storeModel.recordOpenConnectionsAndInitCachesStarted(cosmosContainerIdentities); } private static SqlQuerySpec createLogicalPartitionScanQuerySpec( PartitionKey partitionKey, String partitionKeySelector) { StringBuilder queryStringBuilder = new StringBuilder(); List<SqlParameter> parameters = new ArrayList<>(); queryStringBuilder.append("SELECT * FROM c WHERE"); Object pkValue = ModelBridgeInternal.getPartitionKeyObject(partitionKey); String pkParamName = "@pkValue"; parameters.add(new SqlParameter(pkParamName, pkValue)); queryStringBuilder.append(" c"); queryStringBuilder.append(partitionKeySelector); queryStringBuilder.append((" = ")); queryStringBuilder.append(pkParamName); return new SqlQuerySpec(queryStringBuilder.toString(), parameters); } @Override public Mono<List<FeedRange>> getFeedRanges(String collectionLink) { InvalidPartitionExceptionRetryPolicy invalidPartitionExceptionRetryPolicy = new InvalidPartitionExceptionRetryPolicy( this.collectionCache, null, collectionLink, new HashMap<>()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( this, OperationType.Query, ResourceType.Document, collectionLink, null); invalidPartitionExceptionRetryPolicy.onBeforeSendRequest(request); return ObservableHelper.inlineIfPossibleAsObs( () -> getFeedRangesInternal(request, collectionLink), invalidPartitionExceptionRetryPolicy); } private Mono<List<FeedRange>> getFeedRangesInternal(RxDocumentServiceRequest request, String collectionLink) { logger.debug("getFeedRange collectionLink=[{}]", collectionLink); if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); } Mono<Utils.ValueHolder<DocumentCollection>> collectionObs = collectionCache.resolveCollectionAsync(null, request); return collectionObs.flatMap(documentCollectionResourceResponse -> { final DocumentCollection collection = documentCollectionResourceResponse.v; if (collection == null) { return Mono.error(new IllegalStateException("Collection cannot be null")); } Mono<Utils.ValueHolder<List<PartitionKeyRange>>> valueHolderMono = partitionKeyRangeCache .tryGetOverlappingRangesAsync( BridgeInternal.getMetaDataDiagnosticContext(request.requestContext.cosmosDiagnostics), collection.getResourceId(), RANGE_INCLUDING_ALL_PARTITION_KEY_RANGES, true, null); return valueHolderMono.map(partitionKeyRangeList -> toFeedRanges(partitionKeyRangeList, request)); }); } private static List<FeedRange> toFeedRanges( Utils.ValueHolder<List<PartitionKeyRange>> partitionKeyRangeListValueHolder, RxDocumentServiceRequest request) { final List<PartitionKeyRange> partitionKeyRangeList = partitionKeyRangeListValueHolder.v; if (partitionKeyRangeList == null) { request.forceNameCacheRefresh = true; throw new InvalidPartitionException(); } List<FeedRange> feedRanges = new ArrayList<>(); partitionKeyRangeList.forEach(pkRange -> feedRanges.add(toFeedRange(pkRange))); return feedRanges; } private static FeedRange toFeedRange(PartitionKeyRange pkRange) { return new FeedRangeEpkImpl(pkRange.toRange()); } }
As discussed, Will deal with diagnostic and validating diagnostics separately.
public void clientLevelEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosClientBuilder builder = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig) .credential(credential); try (CosmosAsyncClient cosmosAsyncClient = builder.buildAsyncClient()) { String dbname = "db_" + UUID.randomUUID(); String containerName = "container_" + UUID.randomUUID(); CosmosContainerProperties properties = new CosmosContainerProperties(containerName, "/mypk"); cosmosAsyncClient.createDatabaseIfNotExists(dbname).block(); cosmosAsyncClient.getDatabase(dbname) .createContainerIfNotExists(properties).block(); CosmosAsyncContainer container = cosmosAsyncClient.getDatabase(dbname) .getContainer(containerName); TestObject obj = new TestObject(UUID.randomUUID().toString(), "name123", 2, UUID.randomUUID().toString()); CosmosItemResponse response = container.createItem(obj).block(); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = container.readItem(obj.id, new PartitionKey(obj.mypk), TestObject.class); StepVerifier.create(cosmosItemResponseMono) .expectNextCount(1) .expectComplete() .verify(); injectFailure(container, FaultInjectionOperationType.READ_ITEM, null); verifyExpectError(cosmosItemResponseMono); String queryText = "select top 1 * from c"; SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(queryText); CosmosPagedFlux<TestObject> queryPagedFlux = container.queryItems(sqlQuerySpec, TestObject.class); StepVerifier.create(queryPagedFlux) .expectNextCount(1) .expectComplete() .verify(); injectFailure(container, FaultInjectionOperationType.QUERY_ITEM, null); StepVerifier.create(queryPagedFlux) .expectErrorMatches(throwable -> throwable instanceof RequestCancelledException) .verify(); CosmosItemRequestOptions options = new CosmosItemRequestOptions() .setCosmosEndToEndOperationLatencyPolicyConfig(CosmosEndToEndOperationLatencyPolicyConfig.DISABLED); cosmosItemResponseMono = container.readItem(obj.id, new PartitionKey(obj.mypk), options, TestObject.class); StepVerifier.create(cosmosItemResponseMono) .expectNextCount(1) .expectComplete() .verify(); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions() .setCosmosEndToEndOperationLatencyPolicyConfig(CosmosEndToEndOperationLatencyPolicyConfig.DISABLED); queryPagedFlux = container.queryItems(sqlQuerySpec, queryRequestOptions, TestObject.class); StepVerifier.create(queryPagedFlux) .expectNextCount(1) .expectComplete() .verify(); cosmosAsyncClient.getDatabase(dbname).delete().block(); } }
.expectErrorMatches(throwable -> throwable instanceof RequestCancelledException)
public void clientLevelEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosClientBuilder builder = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .endToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig) .credential(credential); try (CosmosAsyncClient cosmosAsyncClient = builder.buildAsyncClient()) { String dbname = "db_" + UUID.randomUUID(); String containerName = "container_" + UUID.randomUUID(); CosmosContainerProperties properties = new CosmosContainerProperties(containerName, "/mypk"); cosmosAsyncClient.createDatabaseIfNotExists(dbname).block(); cosmosAsyncClient.getDatabase(dbname) .createContainerIfNotExists(properties).block(); CosmosAsyncContainer container = cosmosAsyncClient.getDatabase(dbname) .getContainer(containerName); TestObject obj = new TestObject(UUID.randomUUID().toString(), "name123", 2, UUID.randomUUID().toString()); CosmosItemResponse response = container.createItem(obj).block(); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = container.readItem(obj.id, new PartitionKey(obj.mypk), TestObject.class); StepVerifier.create(cosmosItemResponseMono) .expectNextCount(1) .expectComplete() .verify(); injectFailure(container, FaultInjectionOperationType.READ_ITEM, null); verifyExpectError(cosmosItemResponseMono); String queryText = "select top 1 * from c"; SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(queryText); CosmosPagedFlux<TestObject> queryPagedFlux = container.queryItems(sqlQuerySpec, TestObject.class); StepVerifier.create(queryPagedFlux) .expectNextCount(1) .expectComplete() .verify(); injectFailure(container, FaultInjectionOperationType.QUERY_ITEM, null); StepVerifier.create(queryPagedFlux) .expectErrorMatches(throwable -> throwable instanceof OperationCancelledException) .verify(); CosmosItemRequestOptions options = new CosmosItemRequestOptions() .setCosmosEndToEndOperationLatencyPolicyConfig( new CosmosE2EOperationRetryPolicyConfigBuilder(Duration.ofSeconds(1)) .enable(false) .build()); cosmosItemResponseMono = container.readItem(obj.id, new PartitionKey(obj.mypk), options, TestObject.class); StepVerifier.create(cosmosItemResponseMono) .expectNextCount(1) .expectComplete() .verify(); CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions() .setCosmosEndToEndOperationLatencyPolicyConfig( new CosmosE2EOperationRetryPolicyConfigBuilder(Duration.ofSeconds(1)) .enable(false) .build()); queryPagedFlux = container.queryItems(sqlQuerySpec, queryRequestOptions, TestObject.class); StepVerifier.create(queryPagedFlux) .expectNextCount(1) .expectComplete() .verify(); cosmosAsyncClient.getDatabase(dbname).delete().block(); } }
class EndToEndTimeOutValidationTests extends TestSuiteBase { private static final int DEFAULT_NUM_DOCUMENTS = 100; private static final int DEFAULT_PAGE_SIZE = 100; private CosmosAsyncContainer createdContainer; private final Random random; private final List<TestObject> createdDocuments = new ArrayList<>(); private final CosmosEndToEndOperationLatencyPolicyConfig endToEndOperationLatencyPolicyConfig; @Factory(dataProvider = "clientBuildersWithDirectTcpSession") public EndToEndTimeOutValidationTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); random = new Random(); endToEndOperationLatencyPolicyConfig = new CosmosEndToEndOperationLatencyPolicyConfigBuilder() .endToEndOperationTimeout(Duration.ofSeconds(1)) .build(); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT * 100) public void beforeClass() throws Exception { CosmosAsyncClient client = this.getClientBuilder().buildAsyncClient(); CosmosAsyncDatabase createdDatabase = getSharedCosmosDatabase(client); createdContainer = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdContainer); createdDocuments.addAll(this.insertDocuments(DEFAULT_NUM_DOCUMENTS, null, createdContainer)); } @Test(groups = {"simple"}, timeOut = 10000L) public void readItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject itemToRead = createdDocuments.get(random.nextInt(createdDocuments.size())); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.READ_ITEM, null); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.readItem(itemToRead.id, new PartitionKey(itemToRead.mypk), options, TestObject.class); verifyExpectError(cosmosItemResponseMono); rule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void createItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); FaultInjectionRule faultInjectionRule = injectFailure(createdContainer, FaultInjectionOperationType.CREATE_ITEM, null); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.createItem(inputObject, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); faultInjectionRule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void replaceItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); createdContainer.createItem(inputObject, new PartitionKey(inputObject.mypk), options).block(); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.REPLACE_ITEM, null); inputObject.setName("replaceName"); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.replaceItem(inputObject, inputObject.id, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); rule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void upsertItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.UPSERT_ITEM, null); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.upsertItem(inputObject, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); rule.disable(); } private static void verifyExpectError(Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono) { StepVerifier.create(cosmosItemResponseMono) .expectErrorMatches(throwable -> throwable instanceof RequestCancelledException) .verify(); } @Test(groups = {"simple"}, timeOut = 10000L) public void queryItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosEndToEndOperationLatencyPolicyConfig endToEndOperationLatencyPolicyConfig = new CosmosEndToEndOperationLatencyPolicyConfigBuilder() .endToEndOperationTimeout(Duration.ofSeconds(1)) .build(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject itemToQuery = createdDocuments.get(random.nextInt(createdDocuments.size())); String queryText = "select top 1 * from c"; SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(queryText); injectFailure(createdContainer, FaultInjectionOperationType.QUERY_ITEM, null); CosmosPagedFlux<TestObject> queryPagedFlux = createdContainer.queryItems(sqlQuerySpec, options, TestObject.class); StepVerifier.create(queryPagedFlux) .expectErrorMatches(throwable -> throwable instanceof RequestCancelledException) .verify(); } @Test(groups = {"simple"}, timeOut = 10000L) private FaultInjectionRule injectFailure( CosmosAsyncContainer container, FaultInjectionOperationType operationType, Boolean suppressServiceRequests) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofMillis(1500)) .times(1); if (suppressServiceRequests != null) { faultInjectionResultBuilder.suppressServiceRequests(suppressServiceRequests); } IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(operationType) .connectionType(FaultInjectionConnectionType.DIRECT) .build(); FaultInjectionRule rule = new FaultInjectionRuleBuilder("InjectedResponseDelay") .condition(condition) .result(result) .build(); FaultInjectorProvider injectorProvider = (FaultInjectorProvider) container .getOrConfigureFaultInjectorProvider(() -> new FaultInjectorProvider(container)); injectorProvider.configureFaultInjectionRules(Arrays.asList(rule)).block(); return rule; } private TestObject getDocumentDefinition(String documentId, String partitionKey) { int randInt = random.nextInt(DEFAULT_NUM_DOCUMENTS / 2); TestObject doc = new TestObject(documentId, "name" + randInt, randInt, partitionKey); return doc; } private List<TestObject> insertDocuments(int documentCount, List<String> partitionKeys, CosmosAsyncContainer container) { List<TestObject> documentsToInsert = new ArrayList<>(); for (int i = 0; i < documentCount; i++) { documentsToInsert.add( getDocumentDefinition( UUID.randomUUID().toString(), partitionKeys == null ? UUID.randomUUID().toString() : partitionKeys.get(random.nextInt(partitionKeys.size())))); } List<TestObject> documentInserted = bulkInsertBlocking(container, documentsToInsert); waitIfNeededForReplicasToCatchUp(this.getClientBuilder()); return documentInserted; } static class TestObject { String id; String name; int prop; String mypk; String constantProp = "constantProp"; public TestObject() { } public TestObject(String id, String name, int prop, String mypk) { this.id = id; this.name = name; this.prop = prop; this.mypk = mypk; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getProp() { return prop; } public void setProp(final int prop) { this.prop = prop; } public String getMypk() { return mypk; } public void setMypk(String mypk) { this.mypk = mypk; } public String getConstantProp() { return constantProp; } } }
class EndToEndTimeOutValidationTests extends TestSuiteBase { private static final int DEFAULT_NUM_DOCUMENTS = 100; private static final int DEFAULT_PAGE_SIZE = 100; private CosmosAsyncContainer createdContainer; private final Random random; private final List<TestObject> createdDocuments = new ArrayList<>(); private final CosmosE2EOperationRetryPolicyConfig endToEndOperationLatencyPolicyConfig; @Factory(dataProvider = "clientBuildersWithDirectTcpSession") public EndToEndTimeOutValidationTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); random = new Random(); endToEndOperationLatencyPolicyConfig = new CosmosE2EOperationRetryPolicyConfigBuilder(Duration.ofSeconds(1)) .build(); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT * 100) public void beforeClass() throws Exception { CosmosAsyncClient client = this.getClientBuilder().buildAsyncClient(); CosmosAsyncDatabase createdDatabase = getSharedCosmosDatabase(client); createdContainer = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdContainer); createdDocuments.addAll(this.insertDocuments(DEFAULT_NUM_DOCUMENTS, null, createdContainer)); } @Test(groups = {"simple"}, timeOut = 10000L) public void readItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject itemToRead = createdDocuments.get(random.nextInt(createdDocuments.size())); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.READ_ITEM, null); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.readItem(itemToRead.id, new PartitionKey(itemToRead.mypk), options, TestObject.class); verifyExpectError(cosmosItemResponseMono); rule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void createItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); FaultInjectionRule faultInjectionRule = injectFailure(createdContainer, FaultInjectionOperationType.CREATE_ITEM, null); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.createItem(inputObject, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); faultInjectionRule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void replaceItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); createdContainer.createItem(inputObject, new PartitionKey(inputObject.mypk), options).block(); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.REPLACE_ITEM, null); inputObject.setName("replaceName"); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.replaceItem(inputObject, inputObject.id, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); rule.disable(); } @Test(groups = {"simple"}, timeOut = 10000L) public void upsertItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); FaultInjectionRule rule = injectFailure(createdContainer, FaultInjectionOperationType.UPSERT_ITEM, null); TestObject inputObject = new TestObject(UUID.randomUUID().toString(), "name123", 1, UUID.randomUUID().toString()); Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono = createdContainer.upsertItem(inputObject, new PartitionKey(inputObject.mypk), options); verifyExpectError(cosmosItemResponseMono); rule.disable(); } private static void verifyExpectError(Mono<CosmosItemResponse<TestObject>> cosmosItemResponseMono) { StepVerifier.create(cosmosItemResponseMono) .expectErrorMatches(throwable -> throwable instanceof OperationCancelledException) .verify(); } @Test(groups = {"simple"}, timeOut = 10000L) public void queryItemWithEndToEndTimeoutPolicyInOptionsShouldTimeout() { if (getClientBuilder().buildConnectionPolicy().getConnectionMode() != ConnectionMode.DIRECT) { throw new SkipException("Failure injection only supported for DIRECT mode"); } CosmosE2EOperationRetryPolicyConfig endToEndOperationLatencyPolicyConfig = new CosmosE2EOperationRetryPolicyConfigBuilder(Duration.ofSeconds(1)) .build(); CosmosQueryRequestOptions options = new CosmosQueryRequestOptions(); options.setCosmosEndToEndOperationLatencyPolicyConfig(endToEndOperationLatencyPolicyConfig); TestObject itemToQuery = createdDocuments.get(random.nextInt(createdDocuments.size())); String queryText = "select top 1 * from c"; SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(queryText); injectFailure(createdContainer, FaultInjectionOperationType.QUERY_ITEM, null); CosmosPagedFlux<TestObject> queryPagedFlux = createdContainer.queryItems(sqlQuerySpec, options, TestObject.class); StepVerifier.create(queryPagedFlux) .expectErrorMatches(throwable -> throwable instanceof OperationCancelledException && ((OperationCancelledException) throwable).getSubStatusCode() == HttpConstants.SubStatusCodes.CLIENT_OPERATION_TIMEOUT) .verify(); } @Test(groups = {"simple"}, timeOut = 10000L) private FaultInjectionRule injectFailure( CosmosAsyncContainer container, FaultInjectionOperationType operationType, Boolean suppressServiceRequests) { FaultInjectionServerErrorResultBuilder faultInjectionResultBuilder = FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .delay(Duration.ofMillis(1500)) .times(1); if (suppressServiceRequests != null) { faultInjectionResultBuilder.suppressServiceRequests(suppressServiceRequests); } IFaultInjectionResult result = faultInjectionResultBuilder.build(); FaultInjectionCondition condition = new FaultInjectionConditionBuilder() .operationType(operationType) .connectionType(FaultInjectionConnectionType.DIRECT) .build(); FaultInjectionRule rule = new FaultInjectionRuleBuilder("InjectedResponseDelay") .condition(condition) .result(result) .build(); FaultInjectorProvider injectorProvider = (FaultInjectorProvider) container .getOrConfigureFaultInjectorProvider(() -> new FaultInjectorProvider(container)); injectorProvider.configureFaultInjectionRules(Arrays.asList(rule)).block(); return rule; } private TestObject getDocumentDefinition(String documentId, String partitionKey) { int randInt = random.nextInt(DEFAULT_NUM_DOCUMENTS / 2); TestObject doc = new TestObject(documentId, "name" + randInt, randInt, partitionKey); return doc; } private List<TestObject> insertDocuments(int documentCount, List<String> partitionKeys, CosmosAsyncContainer container) { List<TestObject> documentsToInsert = new ArrayList<>(); for (int i = 0; i < documentCount; i++) { documentsToInsert.add( getDocumentDefinition( UUID.randomUUID().toString(), partitionKeys == null ? UUID.randomUUID().toString() : partitionKeys.get(random.nextInt(partitionKeys.size())))); } List<TestObject> documentInserted = bulkInsertBlocking(container, documentsToInsert); waitIfNeededForReplicasToCatchUp(this.getClientBuilder()); return documentInserted; } static class TestObject { String id; String name; int prop; String mypk; String constantProp = "constantProp"; public TestObject() { } public TestObject(String id, String name, int prop, String mypk) { this.id = id; this.name = name; this.prop = prop; this.mypk = mypk; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getProp() { return prop; } public void setProp(final int prop) { this.prop = prop; } public String getMypk() { return mypk; } public void setMypk(String mypk) { this.mypk = mypk; } public String getConstantProp() { return constantProp; } } }
Something is not write here... we were only supposed to add the missing throttling in the onErrorResume such that it prevents the load balancer worker thread to making too many requests towards the lease container...
private Mono<Void> run(CancellationToken cancellationToken) { return Flux.just(this) .flatMap(value -> this.leaseContainer.getAllLeases()) .collectList() .flatMap(allLeases -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); List<Lease> leasesToTake = this.partitionLoadBalancingStrategy.selectLeasesToTake(allLeases); if (leasesToTake.size() > 0) { this.logger.info("Found {} total leases, taking ownership of {}", allLeases.size(), leasesToTake.size()); } if (cancellationToken.isCancellationRequested()) return Mono.empty(); return Flux.fromIterable(leasesToTake) .limitRate(1) .flatMap(lease -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); return this.partitionController.addOrUpdateLease(lease); }) .then(); }) .onErrorResume(throwable -> { logger.warn("Unexpected exception thrown while trying to acquire available leases", throwable); return Mono.empty(); }) .then( Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } Instant stopTimer = Instant.now().plus(this.leaseAcquireInterval); return Mono.just(value) .delayElement(Duration.ofMillis(100), CosmosSchedulers.COSMOS_PARALLEL) .repeat(() -> { Instant currentTime = Instant.now(); return !cancellationToken.isCancellationRequested() && currentTime.isBefore(stopTimer); }) .then(); }) ) .repeat(() -> !cancellationToken.isCancellationRequested()) .then() .onErrorResume(throwable -> { logger.info("Partition load balancer task stopped."); return this.stop(); }); }
.then();
private Mono<Void> run(CancellationToken cancellationToken) { return Flux.just(this) .flatMap(value -> this.leaseContainer.getAllLeases()) .collectList() .flatMap(allLeases -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); List<Lease> leasesToTake = this.partitionLoadBalancingStrategy.selectLeasesToTake(allLeases); if (leasesToTake.size() > 0) { this.logger.info("Found {} total leases, taking ownership of {}", allLeases.size(), leasesToTake.size()); } if (cancellationToken.isCancellationRequested()) return Mono.empty(); return Flux.fromIterable(leasesToTake) .limitRate(1) .flatMap(lease -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); return this.partitionController.addOrUpdateLease(lease); }) .then(); }) .onErrorResume(throwable -> { logger.warn("Unexpected exception thrown while trying to acquire available leases", throwable); return Mono.empty(); }) .then( Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } Instant stopTimer = Instant.now().plus(this.leaseAcquireInterval); return Mono.just(value) .delayElement(Duration.ofMillis(100), CosmosSchedulers.COSMOS_PARALLEL) .repeat(() -> { Instant currentTime = Instant.now(); return !cancellationToken.isCancellationRequested() && currentTime.isBefore(stopTimer); }) .then(); }) ) .repeat(() -> !cancellationToken.isCancellationRequested()) .then() .onErrorResume(throwable -> { logger.info("Partition load balancer task stopped."); return this.stop(); }); }
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalancingStrategy; private final Duration leaseAcquireInterval; private final Scheduler scheduler; private CancellationTokenSource cancellationTokenSource; private volatile boolean started; private final Object lock; public PartitionLoadBalancerImpl( PartitionController partitionController, LeaseContainer leaseContainer, PartitionLoadBalancingStrategy partitionLoadBalancingStrategy, Duration leaseAcquireInterval, Scheduler scheduler) { checkNotNull(partitionController, "Argument 'partitionController' can not be null"); checkNotNull(leaseContainer, "Argument 'leaseContainer' can not be null"); checkNotNull(partitionLoadBalancingStrategy, "Argument 'partitionLoadBalancingStrategy' can not be null"); checkNotNull(scheduler, "Argument 'scheduler' can not be null"); this.partitionController = partitionController; this.leaseContainer = leaseContainer; this.partitionLoadBalancingStrategy = partitionLoadBalancingStrategy; this.leaseAcquireInterval = leaseAcquireInterval; this.scheduler = scheduler; this.started = false; this.lock = new Object(); } @Override public Mono<Void> start() { synchronized (lock) { if (this.started) { throw new IllegalStateException("Partition load balancer already started"); } this.cancellationTokenSource = new CancellationTokenSource(); this.started = true; } return Mono.fromRunnable( () -> { scheduler.schedule(() -> this.run(this.cancellationTokenSource.getToken()).subscribe()); }); } @Override public Mono<Void> stop() { synchronized (lock) { this.started = false; this.cancellationTokenSource.cancel(); } return this.partitionController.shutdown(); } @Override public boolean isRunning() { return this.started; } }
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalancingStrategy; private final Duration leaseAcquireInterval; private final Scheduler scheduler; private CancellationTokenSource cancellationTokenSource; private volatile boolean started; private final Object lock; public PartitionLoadBalancerImpl( PartitionController partitionController, LeaseContainer leaseContainer, PartitionLoadBalancingStrategy partitionLoadBalancingStrategy, Duration leaseAcquireInterval, Scheduler scheduler) { checkNotNull(partitionController, "Argument 'partitionController' can not be null"); checkNotNull(leaseContainer, "Argument 'leaseContainer' can not be null"); checkNotNull(partitionLoadBalancingStrategy, "Argument 'partitionLoadBalancingStrategy' can not be null"); checkNotNull(scheduler, "Argument 'scheduler' can not be null"); this.partitionController = partitionController; this.leaseContainer = leaseContainer; this.partitionLoadBalancingStrategy = partitionLoadBalancingStrategy; this.leaseAcquireInterval = leaseAcquireInterval; this.scheduler = scheduler; this.started = false; this.lock = new Object(); } @Override public Mono<Void> start() { synchronized (lock) { if (this.started) { throw new IllegalStateException("Partition load balancer already started"); } this.cancellationTokenSource = new CancellationTokenSource(); this.started = true; } return Mono.fromRunnable( () -> { scheduler.schedule(() -> this.run(this.cancellationTokenSource.getToken()).subscribe()); }); } @Override public Mono<Void> stop() { synchronized (lock) { this.started = false; this.cancellationTokenSource.cancel(); } return this.partitionController.shutdown(); } @Override public boolean isRunning() { return this.started; } }
Is there a particular reason that only the `KeyVaulRoleScope` class needed this customization?
public void customize(LibraryCustomization libraryCustomization, Logger logger) { libraryCustomization.getPackage("com.azure.security.keyvault.administration.models") .getClass("KeyVaultRoleScope") .customizeAst(ast -> { ast.addImport(IllegalArgumentException.class) .addImport(URL.class) .addImport(MalformedURLException.class); ClassOrInterfaceDeclaration clazz = ast.getClassByName("KeyVaultRoleScope").get(); clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) .setType("KeyVaultRoleScope") .addParameter("String", "url") .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( "/**", " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", " * @param url A string representing a URL containing the name of the scope to look for.", " * @return The corresponding {@link KeyVaultRoleScope}.", " * @throws IllegalArgumentException If the given {@code url} is malformed.", " */" ))) .setBody(StaticJavaParser.parseBlock(joinWithNewline( "{", "try {", " return fromString(new URL(url).getPath());", "} catch (MalformedURLException e) {", " throw new IllegalArgumentException(e);", "}", "}" ))); clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) .setType("KeyVaultRoleScope") .addParameter("URL", "url") .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( "/**", " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", " * @param url A URL containing the name of the scope to look for.", " * @return The corresponding {@link KeyVaultRoleScope}.", " */" ))) .setBody(StaticJavaParser.parseBlock("{return fromString(url.getPath());}")); }); }
.getClass("KeyVaultRoleScope")
public void customize(LibraryCustomization libraryCustomization, Logger logger) { customizeModels(libraryCustomization.getPackage("com.azure.security.keyvault.administration.models")); customizePackageInfos(libraryCustomization.getRawEditor()); }
class RbacCustomizations extends Customization { @Override private static String joinWithNewline(String... lines) { return String.join("\n", lines); } }
class RbacCustomizations extends Customization { @Override private static void customizeModels(PackageCustomization packageCustomization) { customizeKeyVaultRoleScope(packageCustomization.getClass("KeyVaultRoleScope")); } private static void customizeKeyVaultRoleScope(ClassCustomization classCustomization) { classCustomization.customizeAst(ast -> { ast.addImport(IllegalArgumentException.class) .addImport(URL.class) .addImport(MalformedURLException.class); ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get(); clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) .setType("KeyVaultRoleScope") .addParameter("String", "url") .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( "/**", " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", " * @param url A string representing a URL containing the name of the scope to look for.", " * @return The corresponding {@link KeyVaultRoleScope}.", " * @throws IllegalArgumentException If the given {@code url} is malformed.", " */" ))) .setBody(StaticJavaParser.parseBlock(joinWithNewline( "{", "try {", " return fromString(new URL(url).getPath());", "} catch (MalformedURLException e) {", " throw new IllegalArgumentException(e);", "}", "}" ))); clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) .setType("KeyVaultRoleScope") .addParameter("URL", "url") .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( "/**", " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", " * @param url A URL containing the name of the scope to look for.", " * @return The corresponding {@link KeyVaultRoleScope}.", " */" ))) .setBody(StaticJavaParser.parseBlock("{return fromString(url.getPath());}")); }); } private static void customizePackageInfos(Editor editor) { editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/package-info.java", joinWithNewline( " " " "", "/**", " * Package containing classes for creating clients {@link", " * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} and {@link", " * com.azure.security.keyvault.administration.KeyVaultAccessControlClient} that perform access control operations on", " * Azure Key Vault resources, as well as clients {@link", " * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient} and {@link", " * com.azure.security.keyvault.administration.KeyVaultBackupClient} that perform backup and restore operations on Azure", " * Key Vault keys.", " */", "package com.azure.security.keyvault.administration;", "" )); editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/models/package-info.java", joinWithNewline( " " " "", "/**", " * Package containing classes used by {@link", " * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} and {@link", " * com.azure.security.keyvault.administration.KeyVaultAccessControlClient} to perform access control operations on Azure", " * Key Vault resources, as well as classes used by {@link", " * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient} and {@link", " * com.azure.security.keyvault.administration.KeyVaultBackupClient} to perform backup and restore operations on Azure", " * Key Vault keys.", " */", "package com.azure.security.keyvault.administration.models;", "" )); editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/package-info.java", joinWithNewline( " " " "", "/**", " * Package containing the implementations for KeyVaultAccessControlClient, KeyVaultBackupClient, and", " * KeyVaultSettingsClient. The key vault client performs cryptographic key operations and vault operations against the", " * Key Vault service.", " */", "package com.azure.security.keyvault.administration.implementation;", "" )); editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java", joinWithNewline( " " " "", "/**", " * Package containing the data models for KeyVaultAccessControlClient, KeyVaultBackupClient, and KeyVaultSettingsClient.", " * The key vault client performs cryptographic key operations and vault operations against the Key Vault service.", " */", "package com.azure.security.keyvault.administration.implementation.models;", "" )); } private static String joinWithNewline(String... lines) { return String.join("\n", lines); } }
Yeah, it had custom `fromUrl` methods added to the `ExpandableStringEnum` type which aren't common.
public void customize(LibraryCustomization libraryCustomization, Logger logger) { libraryCustomization.getPackage("com.azure.security.keyvault.administration.models") .getClass("KeyVaultRoleScope") .customizeAst(ast -> { ast.addImport(IllegalArgumentException.class) .addImport(URL.class) .addImport(MalformedURLException.class); ClassOrInterfaceDeclaration clazz = ast.getClassByName("KeyVaultRoleScope").get(); clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) .setType("KeyVaultRoleScope") .addParameter("String", "url") .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( "/**", " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", " * @param url A string representing a URL containing the name of the scope to look for.", " * @return The corresponding {@link KeyVaultRoleScope}.", " * @throws IllegalArgumentException If the given {@code url} is malformed.", " */" ))) .setBody(StaticJavaParser.parseBlock(joinWithNewline( "{", "try {", " return fromString(new URL(url).getPath());", "} catch (MalformedURLException e) {", " throw new IllegalArgumentException(e);", "}", "}" ))); clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) .setType("KeyVaultRoleScope") .addParameter("URL", "url") .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( "/**", " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", " * @param url A URL containing the name of the scope to look for.", " * @return The corresponding {@link KeyVaultRoleScope}.", " */" ))) .setBody(StaticJavaParser.parseBlock("{return fromString(url.getPath());}")); }); }
.getClass("KeyVaultRoleScope")
public void customize(LibraryCustomization libraryCustomization, Logger logger) { customizeModels(libraryCustomization.getPackage("com.azure.security.keyvault.administration.models")); customizePackageInfos(libraryCustomization.getRawEditor()); }
class RbacCustomizations extends Customization { @Override private static String joinWithNewline(String... lines) { return String.join("\n", lines); } }
class RbacCustomizations extends Customization { @Override private static void customizeModels(PackageCustomization packageCustomization) { customizeKeyVaultRoleScope(packageCustomization.getClass("KeyVaultRoleScope")); } private static void customizeKeyVaultRoleScope(ClassCustomization classCustomization) { classCustomization.customizeAst(ast -> { ast.addImport(IllegalArgumentException.class) .addImport(URL.class) .addImport(MalformedURLException.class); ClassOrInterfaceDeclaration clazz = ast.getClassByName(classCustomization.getClassName()).get(); clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) .setType("KeyVaultRoleScope") .addParameter("String", "url") .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( "/**", " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", " * @param url A string representing a URL containing the name of the scope to look for.", " * @return The corresponding {@link KeyVaultRoleScope}.", " * @throws IllegalArgumentException If the given {@code url} is malformed.", " */" ))) .setBody(StaticJavaParser.parseBlock(joinWithNewline( "{", "try {", " return fromString(new URL(url).getPath());", "} catch (MalformedURLException e) {", " throw new IllegalArgumentException(e);", "}", "}" ))); clazz.addMethod("fromUrl", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) .setType("KeyVaultRoleScope") .addParameter("URL", "url") .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( "/**", " * Creates of finds a {@link KeyVaultRoleScope} from its string representation.", " *", " * @param url A URL containing the name of the scope to look for.", " * @return The corresponding {@link KeyVaultRoleScope}.", " */" ))) .setBody(StaticJavaParser.parseBlock("{return fromString(url.getPath());}")); }); } private static void customizePackageInfos(Editor editor) { editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/package-info.java", joinWithNewline( " " " "", "/**", " * Package containing classes for creating clients {@link", " * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} and {@link", " * com.azure.security.keyvault.administration.KeyVaultAccessControlClient} that perform access control operations on", " * Azure Key Vault resources, as well as clients {@link", " * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient} and {@link", " * com.azure.security.keyvault.administration.KeyVaultBackupClient} that perform backup and restore operations on Azure", " * Key Vault keys.", " */", "package com.azure.security.keyvault.administration;", "" )); editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/models/package-info.java", joinWithNewline( " " " "", "/**", " * Package containing classes used by {@link", " * com.azure.security.keyvault.administration.KeyVaultAccessControlAsyncClient} and {@link", " * com.azure.security.keyvault.administration.KeyVaultAccessControlClient} to perform access control operations on Azure", " * Key Vault resources, as well as classes used by {@link", " * com.azure.security.keyvault.administration.KeyVaultBackupAsyncClient} and {@link", " * com.azure.security.keyvault.administration.KeyVaultBackupClient} to perform backup and restore operations on Azure", " * Key Vault keys.", " */", "package com.azure.security.keyvault.administration.models;", "" )); editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/package-info.java", joinWithNewline( " " " "", "/**", " * Package containing the implementations for KeyVaultAccessControlClient, KeyVaultBackupClient, and", " * KeyVaultSettingsClient. The key vault client performs cryptographic key operations and vault operations against the", " * Key Vault service.", " */", "package com.azure.security.keyvault.administration.implementation;", "" )); editor.replaceFile("src/main/java/com/azure/security/keyvault/administration/implementation/models/package-info.java", joinWithNewline( " " " "", "/**", " * Package containing the data models for KeyVaultAccessControlClient, KeyVaultBackupClient, and KeyVaultSettingsClient.", " * The key vault client performs cryptographic key operations and vault operations against the Key Vault service.", " */", "package com.azure.security.keyvault.administration.implementation.models;", "" )); } private static String joinWithNewline(String... lines) { return String.join("\n", lines); } }
this is added to debug the failed tests in CI pipeline, will remove afterwards
public void faultInjectionServerErrorRuleTests_OperationTypeImpactAddresses(OperationType operationType) throws JsonProcessingException { TestItem createdItem = TestItem.createNewItem(); this.cosmosAsyncContainer.createItem(createdItem).block(); String writeRegionServerGoneRuleId = "serverErrorRule-writeRegionOnly-" + UUID.randomUUID(); FaultInjectionRule writeRegionServerGoneErrorRule = new FaultInjectionRuleBuilder(writeRegionServerGoneRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); String primaryReplicaServerGoneRuleId = "serverErrorRule-primaryReplicaOnly-" + UUID.randomUUID(); FaultInjectionRule primaryReplicaServerGoneErrorRule = new FaultInjectionRuleBuilder(primaryReplicaServerGoneRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .endpoints( new FaultInjectionEndpointBuilder(FeedRange.forLogicalPartition(new PartitionKey(createdItem.getId()))) .replicaCount(3) .build()) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); List<String> preferredRegionList = new ArrayList<>(); for (String region : this.readRegionMap.keySet()) { if (this.writeRegionMap.containsKey(region)) { preferredRegionList.add(region); } else { preferredRegionList.add(0, region); } } logger.info("Inside fault injection test, OperationType {}, write region {}, read region", operationType, this.writeRegionMap.values(), this.readRegionMap.values()); CosmosAsyncClient clientWithPreferredRegions; try { clientWithPreferredRegions = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .preferredRegions(preferredRegionList) .consistencyLevel(ConsistencyLevel.EVENTUAL) .buildAsyncClient(); CosmosAsyncContainer container = clientWithPreferredRegions .getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(writeRegionServerGoneErrorRule)).block(); assertThat(writeRegionServerGoneErrorRule.getRegionEndpoints().size()).isEqualTo(this.writeRegionMap.size() + 1); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, operationType, createdItem); if (operationType.isWriteOperation()) { this.validateHitCount(writeRegionServerGoneErrorRule, 1, operationType, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, operationType, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, writeRegionServerGoneRuleId, true); } else { this.validateNoFaultInjectionApplied(cosmosDiagnostics, operationType, FAULT_INJECTION_RULE_NON_APPLICABLE_ADDRESS); } writeRegionServerGoneErrorRule.disable(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(primaryReplicaServerGoneErrorRule)).block(); assertThat(primaryReplicaServerGoneErrorRule.getRegionEndpoints().size()).isEqualTo(this.writeRegionMap.size() + 1); assertThat(primaryReplicaServerGoneErrorRule.getRegionEndpoints().containsAll(this.writeRegionMap.values())).isTrue(); assertThat(primaryReplicaServerGoneErrorRule.getAddresses().size()).isEqualTo(this.writeRegionMap.size()); } finally { writeRegionServerGoneErrorRule.disable(); primaryReplicaServerGoneErrorRule.disable(); } }
logger.info("Inside fault injection test, OperationType {}, write region {}, read region", operationType, this.writeRegionMap.values(), this.readRegionMap.values());
public void faultInjectionServerErrorRuleTests_OperationTypeImpactAddresses(OperationType operationType) throws JsonProcessingException { TestItem createdItem = TestItem.createNewItem(); this.cosmosAsyncContainer.createItem(createdItem).block(); String writeRegionServerGoneRuleId = "serverErrorRule-writeRegionOnly-" + UUID.randomUUID(); FaultInjectionRule writeRegionServerGoneErrorRule = new FaultInjectionRuleBuilder(writeRegionServerGoneRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); String primaryReplicaServerGoneRuleId = "serverErrorRule-primaryReplicaOnly-" + UUID.randomUUID(); FaultInjectionRule primaryReplicaServerGoneErrorRule = new FaultInjectionRuleBuilder(primaryReplicaServerGoneRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .endpoints( new FaultInjectionEndpointBuilder(FeedRange.forLogicalPartition(new PartitionKey(createdItem.getId()))) .replicaCount(3) .build()) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); List<String> preferredRegionList = new ArrayList<>(); for (String region : this.readRegionMap.keySet()) { if (this.writeRegionMap.containsKey(region)) { preferredRegionList.add(region); } else { preferredRegionList.add(0, region); } } logger.info( "Inside fault injection test, OperationType {}, write region {}, read region", operationType, this.writeRegionMap.values(), this.readRegionMap.values()); CosmosAsyncClient clientWithPreferredRegions; try { clientWithPreferredRegions = new CosmosClientBuilder() .key(TestConfigurations.MASTER_KEY) .endpoint(TestConfigurations.HOST) .preferredRegions(preferredRegionList) .consistencyLevel(ConsistencyLevel.EVENTUAL) .buildAsyncClient(); CosmosAsyncContainer container = clientWithPreferredRegions .getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(writeRegionServerGoneErrorRule)).block(); assertThat(writeRegionServerGoneErrorRule.getRegionEndpoints().size()).isEqualTo(this.writeRegionMap.size() + 1); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, operationType, createdItem); if (operationType.isWriteOperation()) { this.validateHitCount(writeRegionServerGoneErrorRule, 1, operationType, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, operationType, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, writeRegionServerGoneRuleId, true); } else { this.validateNoFaultInjectionApplied(cosmosDiagnostics, operationType, FAULT_INJECTION_RULE_NON_APPLICABLE_ADDRESS); } writeRegionServerGoneErrorRule.disable(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(primaryReplicaServerGoneErrorRule)).block(); assertThat(primaryReplicaServerGoneErrorRule.getRegionEndpoints().size()).isEqualTo(this.writeRegionMap.size() + 1); assertThat(primaryReplicaServerGoneErrorRule.getRegionEndpoints().containsAll(this.writeRegionMap.values())).isTrue(); assertThat(primaryReplicaServerGoneErrorRule.getAddresses().size()).isEqualTo(this.writeRegionMap.size()); } finally { writeRegionServerGoneErrorRule.disable(); primaryReplicaServerGoneErrorRule.disable(); } }
class FaultInjectionServerErrorRuleTests extends TestSuiteBase { private static final int TIMEOUT = 60000; private static final String FAULT_INJECTION_RULE_NON_APPLICABLE_ADDRESS = "Addresses mismatch"; private static final String FAULT_INJECTION_RULE_NON_APPLICABLE_OPERATION_TYPE = "OperationType mismatch"; private static final String FAULT_INJECTION_RULE_NON_APPLICABLE_REGION_ENDPOINT = "RegionEndpoint mismatch"; private static final String FAULT_INJECTION_RULE_NON_APPLICABLE_HIT_LIMIT = "Hit Limit reached"; private CosmosAsyncClient client; private CosmosAsyncContainer cosmosAsyncContainer; private DatabaseAccount databaseAccount; private Map<String, String> readRegionMap; private Map<String, String> writeRegionMap; @Factory(dataProvider = "simpleClientBuildersWithJustDirectTcp") public FaultInjectionServerErrorRuleTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); this.subscriberValidationTimeout = TIMEOUT; } @BeforeClass(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void beforeClass() { client = getClientBuilder().buildAsyncClient(); AsyncDocumentClient asyncDocumentClient = BridgeInternal.getContextClient(client); GlobalEndpointManager globalEndpointManager = asyncDocumentClient.getGlobalEndpointManager(); DatabaseAccount databaseAccount = globalEndpointManager.getLatestDatabaseAccount(); this.databaseAccount = databaseAccount; this.cosmosAsyncContainer = getSharedMultiPartitionCosmosContainerWithIdAsPartitionKey(client); this.readRegionMap = this.getRegionMap(databaseAccount, false); this.writeRegionMap = this.getRegionMap(databaseAccount, true); } @DataProvider(name = "operationTypeProvider") public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Delete }, { OperationType.Query }, { OperationType.Patch } }; } @DataProvider(name = "faultInjectionOperationTypeProvider") public static Object[][] faultInjectionOperationTypeProvider() { return new Object[][]{ { FaultInjectionOperationType.READ_ITEM, false }, { FaultInjectionOperationType.REPLACE_ITEM, true }, { FaultInjectionOperationType.CREATE_ITEM, true }, { FaultInjectionOperationType.DELETE_ITEM, true}, { FaultInjectionOperationType.QUERY_ITEM, false }, { FaultInjectionOperationType.PATCH_ITEM, true } }; } @DataProvider(name = "faultInjectionServerErrorResponseProvider") public static Object[][] faultInjectionServerErrorResponseProvider() { return new Object[][]{ { FaultInjectionServerErrorType.INTERNAL_SERVER_ERROR, false, 500, 0 }, { FaultInjectionServerErrorType.RETRY_WITH, true, 449, 0 }, { FaultInjectionServerErrorType.TOO_MANY_REQUEST, true, 429, 0 }, { FaultInjectionServerErrorType.READ_SESSION_NOT_AVAILABLE, true, 404, 1002 }, { FaultInjectionServerErrorType.TIMEOUT, false, 408, 0 }, { FaultInjectionServerErrorType.PARTITION_IS_MIGRATING, true, 410, 1008 }, { FaultInjectionServerErrorType.PARTITION_IS_SPLITTING, true, 410, 1007 } }; } @Test(groups = {"multi-region", "simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_OperationType(OperationType operationType) throws JsonProcessingException { String serverGoneRuleId = "serverErrorRule-serverGone-" + UUID.randomUUID(); FaultInjectionRule serverGoneErrorRule = new FaultInjectionRuleBuilder(serverGoneRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.READ_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); String tooManyRequestsRuleId = "serverErrorRule-tooManyRequests-" + UUID.randomUUID(); FaultInjectionRule serverTooManyRequestsErrorRule = new FaultInjectionRuleBuilder(tooManyRequestsRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.READ_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.TOO_MANY_REQUEST) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { TestItem createdItem = TestItem.createNewItem(); cosmosAsyncContainer.createItem(createdItem).block(); CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverGoneErrorRule)).block(); assertThat(serverGoneErrorRule.getAddresses().size()).isZero(); assertThat(serverGoneErrorRule.getRegionEndpoints().size() == this.readRegionMap.size() + 1 && serverGoneErrorRule.getRegionEndpoints().containsAll(this.readRegionMap.values())); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(cosmosAsyncContainer, operationType, createdItem); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, operationType, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, serverGoneRuleId, true); serverGoneErrorRule.disable(); CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverTooManyRequestsErrorRule)).block(); assertThat(serverGoneErrorRule.getAddresses().size()).isZero(); assertThat(serverGoneErrorRule.getRegionEndpoints().size() == this.readRegionMap.size() + 1 && serverGoneErrorRule.getRegionEndpoints().containsAll(this.readRegionMap.values())); cosmosDiagnostics = this.performDocumentOperation(cosmosAsyncContainer, operationType, createdItem); if (operationType == OperationType.Read) { this.validateHitCount(serverTooManyRequestsErrorRule, 1, OperationType.Read, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, operationType, HttpConstants.StatusCodes.TOO_MANY_REQUESTS, HttpConstants.SubStatusCodes.UNKNOWN, tooManyRequestsRuleId, true); } else { this.validateNoFaultInjectionApplied(cosmosDiagnostics, operationType, FAULT_INJECTION_RULE_NON_APPLICABLE_OPERATION_TYPE); } } finally { serverGoneErrorRule.disable(); serverTooManyRequestsErrorRule.disable(); } } @Test(groups = {"multi-region"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) @Test(groups = {"multi-region"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_Region() throws JsonProcessingException { List<String> preferredLocations = this.readRegionMap.keySet().stream().collect(Collectors.toList()); CosmosAsyncClient clientWithPreferredRegion = null; String localRegionRuleId = "ServerErrorRule-LocalRegion-" + UUID.randomUUID(); FaultInjectionRule serverErrorRuleLocalRegion = new FaultInjectionRuleBuilder(localRegionRuleId) .condition( new FaultInjectionConditionBuilder() .region(preferredLocations.get(0)) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); String remoteRegionRuleId = "ServerErrorRule-RemoteRegion-" + UUID.randomUUID(); FaultInjectionRule serverErrorRuleRemoteRegion = new FaultInjectionRuleBuilder(remoteRegionRuleId) .condition( new FaultInjectionConditionBuilder() .region(preferredLocations.get(1)) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { clientWithPreferredRegion = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .consistencyLevel(BridgeInternal.getContextClient(this.client).getConsistencyLevel()) .preferredRegions(preferredLocations) .directMode() .buildAsyncClient(); CosmosAsyncContainer container = clientWithPreferredRegion .getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); TestItem createdItem = TestItem.createNewItem(); container.createItem(createdItem).block(); CosmosFaultInjectionHelper.configureFaultInjectionRules( container, Arrays.asList(serverErrorRuleLocalRegion, serverErrorRuleRemoteRegion)) .block(); assertThat( serverErrorRuleLocalRegion.getRegionEndpoints().size() == 1 && serverErrorRuleLocalRegion.getRegionEndpoints().get(0).equals(this.readRegionMap.get(preferredLocations.get(0)))); assertThat( serverErrorRuleRemoteRegion.getRegionEndpoints().size() == 1 && serverErrorRuleRemoteRegion.getRegionEndpoints().get(0).equals(this.readRegionMap.get(preferredLocations.get(1)))); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, OperationType.Read, createdItem); this.validateHitCount(serverErrorRuleLocalRegion, 1, OperationType.Read, ResourceType.Document); this.validateHitCount(serverErrorRuleRemoteRegion, 0, OperationType.Read, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Read, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, localRegionRuleId, true ); serverErrorRuleLocalRegion.disable(); cosmosDiagnostics = this.performDocumentOperation(container, OperationType.Read, createdItem); this.validateNoFaultInjectionApplied(cosmosDiagnostics, OperationType.Read, FAULT_INJECTION_RULE_NON_APPLICABLE_REGION_ENDPOINT); } finally { serverErrorRuleLocalRegion.disable(); serverErrorRuleRemoteRegion.disable(); safeClose(clientWithPreferredRegion); } } @Test(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_Partition() throws JsonProcessingException { TestItem createdItem = TestItem.createNewItem(); cosmosAsyncContainer.createItem(createdItem).block(); List<FeedRange> feedRanges = cosmosAsyncContainer.getFeedRanges().block(); String feedRangeRuleId = "ServerErrorRule-FeedRange-" + UUID.randomUUID(); FaultInjectionRule serverErrorRuleByFeedRange = new FaultInjectionRuleBuilder(feedRangeRuleId) .condition( new FaultInjectionConditionBuilder() .endpoints(new FaultInjectionEndpointBuilder(feedRanges.get(0)).build()) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverErrorRuleByFeedRange)).block(); assertThat( serverErrorRuleByFeedRange.getRegionEndpoints().size() == this.readRegionMap.size() && serverErrorRuleByFeedRange.getRegionEndpoints().containsAll(this.readRegionMap.keySet())); assertThat(serverErrorRuleByFeedRange.getAddresses().size()).isBetween( this.readRegionMap.size() * 3, this.readRegionMap.size() * 5); String query = "select * from c"; CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); queryRequestOptions.setFeedRange(feedRanges.get(0)); CosmosDiagnostics cosmosDiagnostics = cosmosAsyncContainer.queryItems(query, queryRequestOptions, TestItem.class).byPage().blockFirst().getCosmosDiagnostics(); this.validateHitCount(serverErrorRuleByFeedRange, 1, OperationType.Query, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Query, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, feedRangeRuleId, true ); queryRequestOptions.setFeedRange(feedRanges.get(1)); try { cosmosDiagnostics = cosmosAsyncContainer.queryItems(query, queryRequestOptions, TestItem.class).byPage().blockFirst().getCosmosDiagnostics(); this.validateNoFaultInjectionApplied(cosmosDiagnostics, OperationType.Query, FAULT_INJECTION_RULE_NON_APPLICABLE_ADDRESS); } finally { serverErrorRuleByFeedRange.disable(); } } @Test(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerResponseDelay() throws JsonProcessingException { CosmosAsyncClient newClient = null; String timeoutRuleId = "serverErrorRule-transitTimeout-" + UUID.randomUUID(); FaultInjectionRule timeoutRule = new FaultInjectionRuleBuilder(timeoutRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.READ_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .times(1) .delay(Duration.ofSeconds(6)) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); directConnectionConfig.setConnectTimeout(Duration.ofSeconds(1)); newClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .consistencyLevel(BridgeInternal.getContextClient(this.client).getConsistencyLevel()) .directMode(directConnectionConfig) .buildAsyncClient(); CosmosAsyncContainer container = newClient .getDatabase(cosmosAsyncContainer.getDatabase().getId()) .getContainer(cosmosAsyncContainer.getId()); TestItem createdItem = TestItem.createNewItem(); container.createItem(createdItem).block(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(timeoutRule)).block(); CosmosItemResponse<TestItem> itemResponse = container.readItem(createdItem.getId(), new PartitionKey(createdItem.getId()), TestItem.class).block(); assertThat(timeoutRule.getHitCount()).isEqualTo(1); this.validateHitCount(timeoutRule, 1, OperationType.Read, ResourceType.Document); this.validateFaultInjectionRuleApplied( itemResponse.getDiagnostics(), OperationType.Read, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.TRANSPORT_GENERATED_410, timeoutRuleId, true ); } finally { timeoutRule.disable(); safeClose(newClient); } } @Test(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerConnectionDelay() throws JsonProcessingException { CosmosAsyncClient newClient = null; String ruleId = "serverErrorRule-serverConnectionDelay-" + UUID.randomUUID(); FaultInjectionRule serverConnectionDelayRule = new FaultInjectionRuleBuilder(ruleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.CONNECTION_DELAY) .delay(Duration.ofSeconds(2)) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); directConnectionConfig.setConnectTimeout(Duration.ofSeconds(1)); newClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .consistencyLevel(BridgeInternal.getContextClient(this.client).getConsistencyLevel()) .directMode(directConnectionConfig) .buildAsyncClient(); CosmosAsyncContainer container = newClient .getDatabase(cosmosAsyncContainer.getDatabase().getId()) .getContainer(cosmosAsyncContainer.getId()); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(serverConnectionDelayRule)).block(); CosmosItemResponse<TestItem> itemResponse = container.createItem(TestItem.createNewItem()).block(); assertThat(serverConnectionDelayRule.getHitCount()).isBetween(1l, 2l); this.validateFaultInjectionRuleApplied( itemResponse.getDiagnostics(), OperationType.Create, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.TRANSPORT_GENERATED_410, ruleId, true ); } finally { serverConnectionDelayRule.disable(); safeClose(newClient); } } @Test(groups = {"multi-region", "simple"}, dataProvider = "faultInjectionOperationTypeProvider", timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerConnectionDelay_warmup( FaultInjectionOperationType operationType, boolean primaryAddressesOnly) { CosmosAsyncClient newClient = null; String ruleId = "serverErrorRule-serverConnectionDelay-warmup" + UUID.randomUUID(); FaultInjectionRule serverConnectionDelayWarmupRule = new FaultInjectionRuleBuilder(ruleId) .condition( new FaultInjectionConditionBuilder() .operationType(operationType) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.CONNECTION_DELAY) .delay(Duration.ofSeconds(2)) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); directConnectionConfig.setConnectTimeout(Duration.ofSeconds(1)); newClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .consistencyLevel(BridgeInternal.getContextClient(this.client).getConsistencyLevel()) .directMode(directConnectionConfig) .buildAsyncClient(); CosmosAsyncContainer container = newClient .getDatabase(cosmosAsyncContainer.getDatabase().getId()) .getContainer(cosmosAsyncContainer.getId()); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(serverConnectionDelayWarmupRule)).block(); int partitionSize = container.getFeedRanges().block().size(); container.openConnectionsAndInitCaches().block(); if (primaryAddressesOnly) { this.validateHitCount(serverConnectionDelayWarmupRule, partitionSize, OperationType.Create, ResourceType.Connection); } else { assertThat(serverConnectionDelayWarmupRule.getHitCount()).isBetween(partitionSize * 3L, partitionSize * 5L); this.validateHitCount( serverConnectionDelayWarmupRule, serverConnectionDelayWarmupRule.getHitCount(), OperationType.Create, ResourceType.Connection); } } finally { serverConnectionDelayWarmupRule.disable(); safeClose(newClient); } } @Test(groups = {"multi-region", "simple"}, dataProvider = "faultInjectionServerErrorResponseProvider", timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerErrorResponse( FaultInjectionServerErrorType serverErrorType, boolean canRetry, int errorStatusCode, int errorSubStatusCode) throws JsonProcessingException { String ruleId = "serverErrorRule-" + serverErrorType + "-" + UUID.randomUUID(); FaultInjectionRule serverErrorRule = new FaultInjectionRuleBuilder(ruleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.READ_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { TestItem createdItem = TestItem.createNewItem(); cosmosAsyncContainer.createItem(createdItem).block(); CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverErrorRule)).block(); CosmosDiagnostics cosmosDiagnostics = null; if (canRetry) { try { cosmosDiagnostics = cosmosAsyncContainer .readItem(createdItem.getId(), new PartitionKey(createdItem.getId()), TestItem.class) .block() .getDiagnostics(); } catch (Exception exception) { fail("Request should succeeded, but failed with " + exception); } } else { try { cosmosDiagnostics = cosmosAsyncContainer .readItem(createdItem.getId(), new PartitionKey(createdItem.getId()), TestItem.class) .block() .getDiagnostics(); fail("Request should fail, but succeeded"); } catch (Exception e) { cosmosDiagnostics = ((CosmosException)e).getDiagnostics(); } } this.validateHitCount(serverErrorRule, 1, OperationType.Read, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Read, errorStatusCode, errorSubStatusCode, ruleId, canRetry ); } finally { serverErrorRule.disable(); } } @Test(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_HitLimit() throws JsonProcessingException { TestItem createdItem = TestItem.createNewItem(); cosmosAsyncContainer.createItem(createdItem).block(); String hitLimitRuleId = "ServerErrorRule-hitLimit-" + UUID.randomUUID(); FaultInjectionRule hitLimitServerErrorRule = new FaultInjectionRuleBuilder(hitLimitRuleId) .condition( new FaultInjectionConditionBuilder() .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .hitLimit(2) .build(); try { CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(hitLimitServerErrorRule)).block(); assertThat( hitLimitServerErrorRule.getRegionEndpoints().size() == this.readRegionMap.size() && hitLimitServerErrorRule.getRegionEndpoints().containsAll(this.readRegionMap.keySet())); assertThat(hitLimitServerErrorRule.getAddresses().size() == 0); for (int i = 1; i <= 3; i++) { CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(cosmosAsyncContainer, OperationType.Read, createdItem); if (i <= 2) { this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Read, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, hitLimitRuleId, true ); } else { cosmosDiagnostics = this.performDocumentOperation(cosmosAsyncContainer, OperationType.Read, createdItem); this.validateNoFaultInjectionApplied(cosmosDiagnostics, OperationType.Read, FAULT_INJECTION_RULE_NON_APPLICABLE_HIT_LIMIT); } } this.validateHitCount(hitLimitServerErrorRule, 2, OperationType.Read, ResourceType.Document); } finally { hitLimitServerErrorRule.disable(); } } @AfterClass(groups = {"multi-region", "simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private CosmosDiagnostics performDocumentOperation( CosmosAsyncContainer cosmosAsyncContainer, OperationType operationType, TestItem createdItem) { try { if (operationType == OperationType.Query) { CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); String query = String.format("SELECT * from c where c.id = '%s'", createdItem.getId()); FeedResponse<TestItem> itemFeedResponse = cosmosAsyncContainer.queryItems(query, queryRequestOptions, TestItem.class).byPage().blockFirst(); return itemFeedResponse.getCosmosDiagnostics(); } if (operationType == OperationType.Read || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.Create || operationType == OperationType.Patch || operationType == OperationType.Upsert) { if (operationType == OperationType.Read) { return cosmosAsyncContainer.readItem( createdItem.getId(), new PartitionKey(createdItem.getId()), TestItem.class).block().getDiagnostics(); } if (operationType == OperationType.Replace) { return cosmosAsyncContainer.replaceItem( createdItem, createdItem.getId(), new PartitionKey(createdItem.getId())).block().getDiagnostics(); } if (operationType == OperationType.Delete) { return cosmosAsyncContainer.deleteItem(createdItem, null).block().getDiagnostics(); } if (operationType == OperationType.Create) { return cosmosAsyncContainer.createItem(TestItem.createNewItem()).block().getDiagnostics(); } if (operationType == OperationType.Upsert) { return cosmosAsyncContainer.upsertItem(TestItem.createNewItem()).block().getDiagnostics(); } if (operationType == OperationType.Patch) { CosmosPatchOperations patchOperations = CosmosPatchOperations .create() .add("newPath", "newPath"); return cosmosAsyncContainer .patchItem(createdItem.getId(), new PartitionKey(createdItem.getId()), patchOperations, TestItem.class) .block().getDiagnostics(); } } throw new IllegalArgumentException("The operation type is not supported"); } catch (CosmosException cosmosException) { return cosmosException.getDiagnostics(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_includePrimary() throws JsonProcessingException { TestItem createdItem = TestItem.createNewItem(); CosmosAsyncContainer singlePartitionContainer = getSharedSinglePartitionCosmosContainer(client); List<FeedRange> feedRanges = singlePartitionContainer.getFeedRanges().block(); String serverGoneIncludePrimaryRuleId = "serverErrorRule-includePrimary-" + UUID.randomUUID(); FaultInjectionRule serverGoneIncludePrimaryErrorRule = new FaultInjectionRuleBuilder(serverGoneIncludePrimaryRuleId) .condition( new FaultInjectionConditionBuilder() .endpoints( new FaultInjectionEndpointBuilder(feedRanges.get(0)) .replicaCount(1) .includePrimary(true) .build() ) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { CosmosFaultInjectionHelper.configureFaultInjectionRules(singlePartitionContainer, Arrays.asList(serverGoneIncludePrimaryErrorRule)).block(); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(singlePartitionContainer, OperationType.Create, createdItem); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Create, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, serverGoneIncludePrimaryRuleId, true); cosmosDiagnostics = this.performDocumentOperation(singlePartitionContainer, OperationType.Upsert, createdItem); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Upsert, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, serverGoneIncludePrimaryRuleId, true); } finally { serverGoneIncludePrimaryErrorRule.disable(); } } private void validateFaultInjectionRuleApplied( CosmosDiagnostics cosmosDiagnostics, OperationType operationType, int statusCode, int subStatusCode, String ruleId, boolean canRetryOnFaultInjectedError) throws JsonProcessingException { List<ObjectNode> diagnosticsNode = new ArrayList<>(); if (operationType == OperationType.Query) { int clientSideDiagnosticsIndex = cosmosDiagnostics.toString().indexOf("[{\"userAgent\""); ArrayNode arrayNode = (ArrayNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString().substring(clientSideDiagnosticsIndex)); for (JsonNode node : arrayNode) { diagnosticsNode.add((ObjectNode) node); } } else { diagnosticsNode.add((ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString())); } for (ObjectNode diagnosticNode : diagnosticsNode) { JsonNode responseStatisticsList = diagnosticNode.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); if (canRetryOnFaultInjectedError) { assertThat(responseStatisticsList.size()).isEqualTo(2); } else { assertThat(responseStatisticsList.size()).isOne(); } JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); assertThat(storeResult.get("statusCode").asInt()).isEqualTo(statusCode); assertThat(storeResult.get("subStatusCode").asInt()).isEqualTo(subStatusCode); assertThat(storeResult.get("faultInjectionRuleId").asText()).isEqualTo(ruleId); } } private void validateNoFaultInjectionApplied( CosmosDiagnostics cosmosDiagnostics, OperationType operationType, String faultInjectionNonApplicableReason) throws JsonProcessingException { List<ObjectNode> diagnosticsNode = new ArrayList<>(); if (operationType == OperationType.Query) { int clientSideDiagnosticsIndex = cosmosDiagnostics.toString().indexOf("[{\"userAgent\""); ArrayNode arrayNode = (ArrayNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString().substring(clientSideDiagnosticsIndex)); for (JsonNode node : arrayNode) { diagnosticsNode.add((ObjectNode) node); } } else { diagnosticsNode.add((ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString())); } for (ObjectNode diagnosticNode : diagnosticsNode) { JsonNode responseStatisticsList = diagnosticNode.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); for (int i = 0; i < responseStatisticsList.size(); i++) { JsonNode storeResult = responseStatisticsList.get(i).get("storeResult"); assertThat(storeResult.get("faultInjectionRuleId")).isNull(); assertThat(storeResult.get("faultInjectionEvaluationResults")).isNotNull(); assertThat(storeResult.get("faultInjectionEvaluationResults").toString().contains(faultInjectionNonApplicableReason)); } assertThat(responseStatisticsList.size()).isOne(); } } private Map<String, String> getRegionMap(DatabaseAccount databaseAccount, boolean writeOnly) { Iterator<DatabaseAccountLocation> locationIterator = writeOnly ? databaseAccount.getWritableLocations().iterator() : databaseAccount.getReadableLocations().iterator(); Map<String, String> regionMap = new ConcurrentHashMap<>(); while (locationIterator.hasNext()) { DatabaseAccountLocation accountLocation = locationIterator.next(); regionMap.put(accountLocation.getName(), accountLocation.getEndpoint()); } return regionMap; } private void validateHitCount( FaultInjectionRule rule, long totalHitCount, OperationType operationType, ResourceType resourceType) { assertThat(rule.getHitCount()).isEqualTo(totalHitCount); if (totalHitCount > 0) { assertThat(rule.getHitCountDetails().size()).isEqualTo(1); assertThat(rule.getHitCountDetails().get(operationType.toString() + "-" + resourceType.toString())).isEqualTo(totalHitCount); } } }
class FaultInjectionServerErrorRuleTests extends TestSuiteBase { private static final int TIMEOUT = 60000; private static final String FAULT_INJECTION_RULE_NON_APPLICABLE_ADDRESS = "Addresses mismatch"; private static final String FAULT_INJECTION_RULE_NON_APPLICABLE_OPERATION_TYPE = "OperationType mismatch"; private static final String FAULT_INJECTION_RULE_NON_APPLICABLE_REGION_ENDPOINT = "RegionEndpoint mismatch"; private static final String FAULT_INJECTION_RULE_NON_APPLICABLE_HIT_LIMIT = "Hit Limit reached"; private CosmosAsyncClient client; private CosmosAsyncContainer cosmosAsyncContainer; private DatabaseAccount databaseAccount; private Map<String, String> readRegionMap; private Map<String, String> writeRegionMap; @Factory(dataProvider = "simpleClientBuildersWithJustDirectTcp") public FaultInjectionServerErrorRuleTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); this.subscriberValidationTimeout = TIMEOUT; } @BeforeClass(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void beforeClass() { client = getClientBuilder().buildAsyncClient(); AsyncDocumentClient asyncDocumentClient = BridgeInternal.getContextClient(client); GlobalEndpointManager globalEndpointManager = asyncDocumentClient.getGlobalEndpointManager(); DatabaseAccount databaseAccount = globalEndpointManager.getLatestDatabaseAccount(); this.databaseAccount = databaseAccount; this.cosmosAsyncContainer = getSharedMultiPartitionCosmosContainerWithIdAsPartitionKey(client); this.readRegionMap = this.getRegionMap(databaseAccount, false); this.writeRegionMap = this.getRegionMap(databaseAccount, true); } @DataProvider(name = "operationTypeProvider") public static Object[][] operationTypeProvider() { return new Object[][]{ { OperationType.Read }, { OperationType.Replace }, { OperationType.Create }, { OperationType.Delete }, { OperationType.Query }, { OperationType.Patch } }; } @DataProvider(name = "faultInjectionOperationTypeProvider") public static Object[][] faultInjectionOperationTypeProvider() { return new Object[][]{ { FaultInjectionOperationType.READ_ITEM, false }, { FaultInjectionOperationType.REPLACE_ITEM, true }, { FaultInjectionOperationType.CREATE_ITEM, true }, { FaultInjectionOperationType.DELETE_ITEM, true}, { FaultInjectionOperationType.QUERY_ITEM, false }, { FaultInjectionOperationType.PATCH_ITEM, true } }; } @DataProvider(name = "faultInjectionServerErrorResponseProvider") public static Object[][] faultInjectionServerErrorResponseProvider() { return new Object[][]{ { FaultInjectionServerErrorType.INTERNAL_SERVER_ERROR, false, 500, 0 }, { FaultInjectionServerErrorType.RETRY_WITH, true, 449, 0 }, { FaultInjectionServerErrorType.TOO_MANY_REQUEST, true, 429, 0 }, { FaultInjectionServerErrorType.READ_SESSION_NOT_AVAILABLE, true, 404, 1002 }, { FaultInjectionServerErrorType.TIMEOUT, false, 408, 0 }, { FaultInjectionServerErrorType.PARTITION_IS_MIGRATING, true, 410, 1008 }, { FaultInjectionServerErrorType.PARTITION_IS_SPLITTING, true, 410, 1007 } }; } @Test(groups = {"multi-region", "simple"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_OperationType(OperationType operationType) throws JsonProcessingException { String serverGoneRuleId = "serverErrorRule-serverGone-" + UUID.randomUUID(); FaultInjectionRule serverGoneErrorRule = new FaultInjectionRuleBuilder(serverGoneRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.READ_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); String tooManyRequestsRuleId = "serverErrorRule-tooManyRequests-" + UUID.randomUUID(); FaultInjectionRule serverTooManyRequestsErrorRule = new FaultInjectionRuleBuilder(tooManyRequestsRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.READ_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.TOO_MANY_REQUEST) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { TestItem createdItem = TestItem.createNewItem(); cosmosAsyncContainer.createItem(createdItem).block(); CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverGoneErrorRule)).block(); assertThat(serverGoneErrorRule.getAddresses().size()).isZero(); assertThat(serverGoneErrorRule.getRegionEndpoints().size() == this.readRegionMap.size() + 1 && serverGoneErrorRule.getRegionEndpoints().containsAll(this.readRegionMap.values())); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(cosmosAsyncContainer, operationType, createdItem); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, operationType, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, serverGoneRuleId, true); serverGoneErrorRule.disable(); CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverTooManyRequestsErrorRule)).block(); assertThat(serverGoneErrorRule.getAddresses().size()).isZero(); assertThat(serverGoneErrorRule.getRegionEndpoints().size() == this.readRegionMap.size() + 1 && serverGoneErrorRule.getRegionEndpoints().containsAll(this.readRegionMap.values())); cosmosDiagnostics = this.performDocumentOperation(cosmosAsyncContainer, operationType, createdItem); if (operationType == OperationType.Read) { this.validateHitCount(serverTooManyRequestsErrorRule, 1, OperationType.Read, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, operationType, HttpConstants.StatusCodes.TOO_MANY_REQUESTS, HttpConstants.SubStatusCodes.UNKNOWN, tooManyRequestsRuleId, true); } else { this.validateNoFaultInjectionApplied(cosmosDiagnostics, operationType, FAULT_INJECTION_RULE_NON_APPLICABLE_OPERATION_TYPE); } } finally { serverGoneErrorRule.disable(); serverTooManyRequestsErrorRule.disable(); } } @Test(groups = {"multi-region"}, dataProvider = "operationTypeProvider", timeOut = TIMEOUT) @Test(groups = {"multi-region"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_Region() throws JsonProcessingException { List<String> preferredLocations = this.readRegionMap.keySet().stream().collect(Collectors.toList()); CosmosAsyncClient clientWithPreferredRegion = null; String localRegionRuleId = "ServerErrorRule-LocalRegion-" + UUID.randomUUID(); FaultInjectionRule serverErrorRuleLocalRegion = new FaultInjectionRuleBuilder(localRegionRuleId) .condition( new FaultInjectionConditionBuilder() .region(preferredLocations.get(0)) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); String remoteRegionRuleId = "ServerErrorRule-RemoteRegion-" + UUID.randomUUID(); FaultInjectionRule serverErrorRuleRemoteRegion = new FaultInjectionRuleBuilder(remoteRegionRuleId) .condition( new FaultInjectionConditionBuilder() .region(preferredLocations.get(1)) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { clientWithPreferredRegion = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .consistencyLevel(BridgeInternal.getContextClient(this.client).getConsistencyLevel()) .preferredRegions(preferredLocations) .directMode() .buildAsyncClient(); CosmosAsyncContainer container = clientWithPreferredRegion .getDatabase(this.cosmosAsyncContainer.getDatabase().getId()) .getContainer(this.cosmosAsyncContainer.getId()); TestItem createdItem = TestItem.createNewItem(); container.createItem(createdItem).block(); CosmosFaultInjectionHelper.configureFaultInjectionRules( container, Arrays.asList(serverErrorRuleLocalRegion, serverErrorRuleRemoteRegion)) .block(); assertThat( serverErrorRuleLocalRegion.getRegionEndpoints().size() == 1 && serverErrorRuleLocalRegion.getRegionEndpoints().get(0).equals(this.readRegionMap.get(preferredLocations.get(0)))); assertThat( serverErrorRuleRemoteRegion.getRegionEndpoints().size() == 1 && serverErrorRuleRemoteRegion.getRegionEndpoints().get(0).equals(this.readRegionMap.get(preferredLocations.get(1)))); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(container, OperationType.Read, createdItem); this.validateHitCount(serverErrorRuleLocalRegion, 1, OperationType.Read, ResourceType.Document); this.validateHitCount(serverErrorRuleRemoteRegion, 0, OperationType.Read, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Read, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, localRegionRuleId, true ); serverErrorRuleLocalRegion.disable(); cosmosDiagnostics = this.performDocumentOperation(container, OperationType.Read, createdItem); this.validateNoFaultInjectionApplied(cosmosDiagnostics, OperationType.Read, FAULT_INJECTION_RULE_NON_APPLICABLE_REGION_ENDPOINT); } finally { serverErrorRuleLocalRegion.disable(); serverErrorRuleRemoteRegion.disable(); safeClose(clientWithPreferredRegion); } } @Test(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_Partition() throws JsonProcessingException { TestItem createdItem = TestItem.createNewItem(); cosmosAsyncContainer.createItem(createdItem).block(); List<FeedRange> feedRanges = cosmosAsyncContainer.getFeedRanges().block(); String feedRangeRuleId = "ServerErrorRule-FeedRange-" + UUID.randomUUID(); FaultInjectionRule serverErrorRuleByFeedRange = new FaultInjectionRuleBuilder(feedRangeRuleId) .condition( new FaultInjectionConditionBuilder() .endpoints(new FaultInjectionEndpointBuilder(feedRanges.get(0)).build()) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverErrorRuleByFeedRange)).block(); assertThat( serverErrorRuleByFeedRange.getRegionEndpoints().size() == this.readRegionMap.size() && serverErrorRuleByFeedRange.getRegionEndpoints().containsAll(this.readRegionMap.keySet())); assertThat(serverErrorRuleByFeedRange.getAddresses().size()).isBetween( this.readRegionMap.size() * 3, this.readRegionMap.size() * 5); String query = "select * from c"; CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); queryRequestOptions.setFeedRange(feedRanges.get(0)); CosmosDiagnostics cosmosDiagnostics = cosmosAsyncContainer.queryItems(query, queryRequestOptions, TestItem.class).byPage().blockFirst().getCosmosDiagnostics(); this.validateHitCount(serverErrorRuleByFeedRange, 1, OperationType.Query, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Query, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, feedRangeRuleId, true ); queryRequestOptions.setFeedRange(feedRanges.get(1)); try { cosmosDiagnostics = cosmosAsyncContainer.queryItems(query, queryRequestOptions, TestItem.class).byPage().blockFirst().getCosmosDiagnostics(); this.validateNoFaultInjectionApplied(cosmosDiagnostics, OperationType.Query, FAULT_INJECTION_RULE_NON_APPLICABLE_ADDRESS); } finally { serverErrorRuleByFeedRange.disable(); } } @Test(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerResponseDelay() throws JsonProcessingException { CosmosAsyncClient newClient = null; String timeoutRuleId = "serverErrorRule-transitTimeout-" + UUID.randomUUID(); FaultInjectionRule timeoutRule = new FaultInjectionRuleBuilder(timeoutRuleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.READ_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.RESPONSE_DELAY) .times(1) .delay(Duration.ofSeconds(6)) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); directConnectionConfig.setConnectTimeout(Duration.ofSeconds(1)); newClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .consistencyLevel(BridgeInternal.getContextClient(this.client).getConsistencyLevel()) .directMode(directConnectionConfig) .buildAsyncClient(); CosmosAsyncContainer container = newClient .getDatabase(cosmosAsyncContainer.getDatabase().getId()) .getContainer(cosmosAsyncContainer.getId()); TestItem createdItem = TestItem.createNewItem(); container.createItem(createdItem).block(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(timeoutRule)).block(); CosmosItemResponse<TestItem> itemResponse = container.readItem(createdItem.getId(), new PartitionKey(createdItem.getId()), TestItem.class).block(); assertThat(timeoutRule.getHitCount()).isEqualTo(1); this.validateHitCount(timeoutRule, 1, OperationType.Read, ResourceType.Document); this.validateFaultInjectionRuleApplied( itemResponse.getDiagnostics(), OperationType.Read, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.TRANSPORT_GENERATED_410, timeoutRuleId, true ); } finally { timeoutRule.disable(); safeClose(newClient); } } @Test(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerConnectionDelay() throws JsonProcessingException { CosmosAsyncClient newClient = null; String ruleId = "serverErrorRule-serverConnectionDelay-" + UUID.randomUUID(); FaultInjectionRule serverConnectionDelayRule = new FaultInjectionRuleBuilder(ruleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.CREATE_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.CONNECTION_DELAY) .delay(Duration.ofSeconds(2)) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); directConnectionConfig.setConnectTimeout(Duration.ofSeconds(1)); newClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .consistencyLevel(BridgeInternal.getContextClient(this.client).getConsistencyLevel()) .directMode(directConnectionConfig) .buildAsyncClient(); CosmosAsyncContainer container = newClient .getDatabase(cosmosAsyncContainer.getDatabase().getId()) .getContainer(cosmosAsyncContainer.getId()); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(serverConnectionDelayRule)).block(); CosmosItemResponse<TestItem> itemResponse = container.createItem(TestItem.createNewItem()).block(); assertThat(serverConnectionDelayRule.getHitCount()).isBetween(1l, 2l); this.validateFaultInjectionRuleApplied( itemResponse.getDiagnostics(), OperationType.Create, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.TRANSPORT_GENERATED_410, ruleId, true ); } finally { serverConnectionDelayRule.disable(); safeClose(newClient); } } @Test(groups = {"multi-region", "simple"}, dataProvider = "faultInjectionOperationTypeProvider", timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerConnectionDelay_warmup( FaultInjectionOperationType operationType, boolean primaryAddressesOnly) { CosmosAsyncClient newClient = null; String ruleId = "serverErrorRule-serverConnectionDelay-warmup" + UUID.randomUUID(); FaultInjectionRule serverConnectionDelayWarmupRule = new FaultInjectionRuleBuilder(ruleId) .condition( new FaultInjectionConditionBuilder() .operationType(operationType) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.CONNECTION_DELAY) .delay(Duration.ofSeconds(2)) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { DirectConnectionConfig directConnectionConfig = DirectConnectionConfig.getDefaultConfig(); directConnectionConfig.setConnectTimeout(Duration.ofSeconds(1)); newClient = new CosmosClientBuilder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .contentResponseOnWriteEnabled(true) .consistencyLevel(BridgeInternal.getContextClient(this.client).getConsistencyLevel()) .directMode(directConnectionConfig) .buildAsyncClient(); CosmosAsyncContainer container = newClient .getDatabase(cosmosAsyncContainer.getDatabase().getId()) .getContainer(cosmosAsyncContainer.getId()); logger.info("serverConnectionDelayWarmupRule: get all the addresses"); List<FeedRange> feedRanges = container.getFeedRanges().block(); for (FeedRange feedRange : feedRanges) { String feedRangeRuleId = "serverErrorRule-test-feedRang" + feedRange.toString(); FaultInjectionRule feedRangeRule = new FaultInjectionRuleBuilder(feedRangeRuleId) .condition( new FaultInjectionConditionBuilder() .endpoints( new FaultInjectionEndpointBuilder(feedRange).build() ) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.TOO_MANY_REQUEST) .build() ) .duration(Duration.ofMinutes(1)) .build(); CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(feedRangeRule)).block(); logger.info("serverConnectionDelayWarmupRul. FeedRange {}, Addresses {}", feedRange, feedRangeRule.getAddresses()); feedRangeRule.disable(); } CosmosFaultInjectionHelper.configureFaultInjectionRules(container, Arrays.asList(serverConnectionDelayWarmupRule)).block(); int partitionSize = container.getFeedRanges().block().size(); container.openConnectionsAndInitCaches().block(); if (primaryAddressesOnly) { logger.info( "serverConnectionDelayWarmupRule. PartitionSize {}, hitCount{}, hitDetails {}", partitionSize, serverConnectionDelayWarmupRule.getHitCount(), serverConnectionDelayWarmupRule.getHitCountDetails()); this.validateHitCount(serverConnectionDelayWarmupRule, partitionSize, OperationType.Create, ResourceType.Connection); } else { assertThat(serverConnectionDelayWarmupRule.getHitCount()).isBetween(partitionSize * 3L, partitionSize * 5L); this.validateHitCount( serverConnectionDelayWarmupRule, serverConnectionDelayWarmupRule.getHitCount(), OperationType.Create, ResourceType.Connection); } } finally { serverConnectionDelayWarmupRule.disable(); safeClose(newClient); } } @Test(groups = {"multi-region", "simple"}, dataProvider = "faultInjectionServerErrorResponseProvider", timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_ServerErrorResponse( FaultInjectionServerErrorType serverErrorType, boolean canRetry, int errorStatusCode, int errorSubStatusCode) throws JsonProcessingException { String ruleId = "serverErrorRule-" + serverErrorType + "-" + UUID.randomUUID(); FaultInjectionRule serverErrorRule = new FaultInjectionRuleBuilder(ruleId) .condition( new FaultInjectionConditionBuilder() .operationType(FaultInjectionOperationType.READ_ITEM) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(serverErrorType) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { TestItem createdItem = TestItem.createNewItem(); cosmosAsyncContainer.createItem(createdItem).block(); CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(serverErrorRule)).block(); CosmosDiagnostics cosmosDiagnostics = null; if (canRetry) { try { cosmosDiagnostics = cosmosAsyncContainer .readItem(createdItem.getId(), new PartitionKey(createdItem.getId()), TestItem.class) .block() .getDiagnostics(); } catch (Exception exception) { fail("Request should succeeded, but failed with " + exception); } } else { try { cosmosDiagnostics = cosmosAsyncContainer .readItem(createdItem.getId(), new PartitionKey(createdItem.getId()), TestItem.class) .block() .getDiagnostics(); fail("Request should fail, but succeeded"); } catch (Exception e) { cosmosDiagnostics = ((CosmosException)e).getDiagnostics(); } } this.validateHitCount(serverErrorRule, 1, OperationType.Read, ResourceType.Document); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Read, errorStatusCode, errorSubStatusCode, ruleId, canRetry ); } finally { serverErrorRule.disable(); } } @Test(groups = {"multi-region", "simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_HitLimit() throws JsonProcessingException { TestItem createdItem = TestItem.createNewItem(); cosmosAsyncContainer.createItem(createdItem).block(); String hitLimitRuleId = "ServerErrorRule-hitLimit-" + UUID.randomUUID(); FaultInjectionRule hitLimitServerErrorRule = new FaultInjectionRuleBuilder(hitLimitRuleId) .condition( new FaultInjectionConditionBuilder() .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .hitLimit(2) .build(); try { CosmosFaultInjectionHelper.configureFaultInjectionRules(cosmosAsyncContainer, Arrays.asList(hitLimitServerErrorRule)).block(); assertThat( hitLimitServerErrorRule.getRegionEndpoints().size() == this.readRegionMap.size() && hitLimitServerErrorRule.getRegionEndpoints().containsAll(this.readRegionMap.keySet())); assertThat(hitLimitServerErrorRule.getAddresses().size() == 0); for (int i = 1; i <= 3; i++) { CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(cosmosAsyncContainer, OperationType.Read, createdItem); if (i <= 2) { this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Read, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, hitLimitRuleId, true ); } else { cosmosDiagnostics = this.performDocumentOperation(cosmosAsyncContainer, OperationType.Read, createdItem); this.validateNoFaultInjectionApplied(cosmosDiagnostics, OperationType.Read, FAULT_INJECTION_RULE_NON_APPLICABLE_HIT_LIMIT); } } this.validateHitCount(hitLimitServerErrorRule, 2, OperationType.Read, ResourceType.Document); } finally { hitLimitServerErrorRule.disable(); } } @AfterClass(groups = {"multi-region", "simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private CosmosDiagnostics performDocumentOperation( CosmosAsyncContainer cosmosAsyncContainer, OperationType operationType, TestItem createdItem) { try { if (operationType == OperationType.Query) { CosmosQueryRequestOptions queryRequestOptions = new CosmosQueryRequestOptions(); String query = String.format("SELECT * from c where c.id = '%s'", createdItem.getId()); FeedResponse<TestItem> itemFeedResponse = cosmosAsyncContainer.queryItems(query, queryRequestOptions, TestItem.class).byPage().blockFirst(); return itemFeedResponse.getCosmosDiagnostics(); } if (operationType == OperationType.Read || operationType == OperationType.Delete || operationType == OperationType.Replace || operationType == OperationType.Create || operationType == OperationType.Patch || operationType == OperationType.Upsert) { if (operationType == OperationType.Read) { return cosmosAsyncContainer.readItem( createdItem.getId(), new PartitionKey(createdItem.getId()), TestItem.class).block().getDiagnostics(); } if (operationType == OperationType.Replace) { return cosmosAsyncContainer.replaceItem( createdItem, createdItem.getId(), new PartitionKey(createdItem.getId())).block().getDiagnostics(); } if (operationType == OperationType.Delete) { return cosmosAsyncContainer.deleteItem(createdItem, null).block().getDiagnostics(); } if (operationType == OperationType.Create) { return cosmosAsyncContainer.createItem(TestItem.createNewItem()).block().getDiagnostics(); } if (operationType == OperationType.Upsert) { return cosmosAsyncContainer.upsertItem(TestItem.createNewItem()).block().getDiagnostics(); } if (operationType == OperationType.Patch) { CosmosPatchOperations patchOperations = CosmosPatchOperations .create() .add("newPath", "newPath"); return cosmosAsyncContainer .patchItem(createdItem.getId(), new PartitionKey(createdItem.getId()), patchOperations, TestItem.class) .block().getDiagnostics(); } } throw new IllegalArgumentException("The operation type is not supported"); } catch (CosmosException cosmosException) { return cosmosException.getDiagnostics(); } } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void faultInjectionServerErrorRuleTests_includePrimary() throws JsonProcessingException { TestItem createdItem = TestItem.createNewItem(); CosmosAsyncContainer singlePartitionContainer = getSharedSinglePartitionCosmosContainer(client); List<FeedRange> feedRanges = singlePartitionContainer.getFeedRanges().block(); String serverGoneIncludePrimaryRuleId = "serverErrorRule-includePrimary-" + UUID.randomUUID(); FaultInjectionRule serverGoneIncludePrimaryErrorRule = new FaultInjectionRuleBuilder(serverGoneIncludePrimaryRuleId) .condition( new FaultInjectionConditionBuilder() .endpoints( new FaultInjectionEndpointBuilder(feedRanges.get(0)) .replicaCount(1) .includePrimary(true) .build() ) .build() ) .result( FaultInjectionResultBuilders .getResultBuilder(FaultInjectionServerErrorType.GONE) .times(1) .build() ) .duration(Duration.ofMinutes(5)) .build(); try { CosmosFaultInjectionHelper.configureFaultInjectionRules(singlePartitionContainer, Arrays.asList(serverGoneIncludePrimaryErrorRule)).block(); CosmosDiagnostics cosmosDiagnostics = this.performDocumentOperation(singlePartitionContainer, OperationType.Create, createdItem); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Create, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, serverGoneIncludePrimaryRuleId, true); cosmosDiagnostics = this.performDocumentOperation(singlePartitionContainer, OperationType.Upsert, createdItem); this.validateFaultInjectionRuleApplied( cosmosDiagnostics, OperationType.Upsert, HttpConstants.StatusCodes.GONE, HttpConstants.SubStatusCodes.UNKNOWN, serverGoneIncludePrimaryRuleId, true); } finally { serverGoneIncludePrimaryErrorRule.disable(); } } private void validateFaultInjectionRuleApplied( CosmosDiagnostics cosmosDiagnostics, OperationType operationType, int statusCode, int subStatusCode, String ruleId, boolean canRetryOnFaultInjectedError) throws JsonProcessingException { List<ObjectNode> diagnosticsNode = new ArrayList<>(); if (operationType == OperationType.Query) { int clientSideDiagnosticsIndex = cosmosDiagnostics.toString().indexOf("[{\"userAgent\""); ArrayNode arrayNode = (ArrayNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString().substring(clientSideDiagnosticsIndex)); for (JsonNode node : arrayNode) { diagnosticsNode.add((ObjectNode) node); } } else { diagnosticsNode.add((ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString())); } for (ObjectNode diagnosticNode : diagnosticsNode) { JsonNode responseStatisticsList = diagnosticNode.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); if (canRetryOnFaultInjectedError) { assertThat(responseStatisticsList.size()).isEqualTo(2); } else { assertThat(responseStatisticsList.size()).isOne(); } JsonNode storeResult = responseStatisticsList.get(0).get("storeResult"); assertThat(storeResult).isNotNull(); assertThat(storeResult.get("statusCode").asInt()).isEqualTo(statusCode); assertThat(storeResult.get("subStatusCode").asInt()).isEqualTo(subStatusCode); assertThat(storeResult.get("faultInjectionRuleId").asText()).isEqualTo(ruleId); } } private void validateNoFaultInjectionApplied( CosmosDiagnostics cosmosDiagnostics, OperationType operationType, String faultInjectionNonApplicableReason) throws JsonProcessingException { List<ObjectNode> diagnosticsNode = new ArrayList<>(); if (operationType == OperationType.Query) { int clientSideDiagnosticsIndex = cosmosDiagnostics.toString().indexOf("[{\"userAgent\""); ArrayNode arrayNode = (ArrayNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString().substring(clientSideDiagnosticsIndex)); for (JsonNode node : arrayNode) { diagnosticsNode.add((ObjectNode) node); } } else { diagnosticsNode.add((ObjectNode) Utils.getSimpleObjectMapper().readTree(cosmosDiagnostics.toString())); } for (ObjectNode diagnosticNode : diagnosticsNode) { JsonNode responseStatisticsList = diagnosticNode.get("responseStatisticsList"); assertThat(responseStatisticsList.isArray()).isTrue(); for (int i = 0; i < responseStatisticsList.size(); i++) { JsonNode storeResult = responseStatisticsList.get(i).get("storeResult"); assertThat(storeResult.get("faultInjectionRuleId")).isNull(); assertThat(storeResult.get("faultInjectionEvaluationResults")).isNotNull(); assertThat(storeResult.get("faultInjectionEvaluationResults").toString().contains(faultInjectionNonApplicableReason)); } assertThat(responseStatisticsList.size()).isOne(); } } private Map<String, String> getRegionMap(DatabaseAccount databaseAccount, boolean writeOnly) { Iterator<DatabaseAccountLocation> locationIterator = writeOnly ? databaseAccount.getWritableLocations().iterator() : databaseAccount.getReadableLocations().iterator(); Map<String, String> regionMap = new ConcurrentHashMap<>(); while (locationIterator.hasNext()) { DatabaseAccountLocation accountLocation = locationIterator.next(); regionMap.put(accountLocation.getName(), accountLocation.getEndpoint()); } return regionMap; } private void validateHitCount( FaultInjectionRule rule, long totalHitCount, OperationType operationType, ResourceType resourceType) { assertThat(rule.getHitCount()).isEqualTo(totalHitCount); if (totalHitCount > 0) { assertThat(rule.getHitCountDetails().size()).isEqualTo(1); assertThat(rule.getHitCountDetails().get(operationType.toString() + "-" + resourceType.toString())).isEqualTo(totalHitCount); } } }
nit: ```suggestion encodedBuffer.rewind(); ``` ? in case there is a mark
private void processSendWork() { if (!hasConnected.get()) { logger.warning("Not connected. Not processing send work."); return; } if (isDisposed.get()) { logger.info("Sender is closed. Not executing work."); return; } while (hasConnected.get() && sender.getCredit() > 0) { final WeightedDeliveryTag weightedDelivery; final RetriableWorkItem workItem; final String deliveryTag; synchronized (pendingSendLock) { weightedDelivery = this.pendingSendsQueue.poll(); if (weightedDelivery != null) { deliveryTag = weightedDelivery.getDeliveryTag(); workItem = this.pendingSendsMap.get(deliveryTag); } else { workItem = null; deliveryTag = null; } } if (workItem == null) { if (deliveryTag != null) { logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .log("sendData not found for this delivery."); } break; } Delivery delivery = null; boolean linkAdvance = false; int sentMsgSize = 0; Exception sendException = null; try { workItem.beforeTry(); delivery = sender.delivery(deliveryTag.getBytes(UTF_8)); delivery.setMessageFormat(workItem.getMessageFormat()); if (workItem.isDeliveryStateProvided()) { delivery.disposition(workItem.getDeliveryState()); } if (workItem.getMessage() != null) { final byte[] encodedBytes = workItem.getMessage(); sentMsgSize = sender.send(encodedBytes, 0, workItem.getEncodedMessageSize()); } else { final ReadableBuffer encodedBuffer = workItem.getEncodedBuffer(); encodedBuffer.position(0); sentMsgSize = sender.send(encodedBuffer); } sentMsgSize = sender.send(workItem.getMessage(), 0, workItem.getEncodedMessageSize()); assert sentMsgSize == workItem.getEncodedMessageSize() : "Contract of the ProtonJ library for Sender. Send API changed"; linkAdvance = sender.advance(); } catch (Exception exception) { sendException = exception; } if (linkAdvance) { logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .log("Sent message."); workItem.setWaitingForAck(); scheduler.schedule(new SendTimeout(deliveryTag), retryOptions.getTryTimeout().toMillis(), TimeUnit.MILLISECONDS); } else { logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .addKeyValue("sentMessageSize", sentMsgSize) .addKeyValue("payloadActualSize", workItem.getEncodedMessageSize()) .log("Sendlink advance failed."); DeliveryState outcome = null; if (delivery != null) { outcome = delivery.getRemoteState(); delivery.free(); } final AmqpErrorContext context = handler.getErrorContext(sender); final Throwable exception = sendException != null ? new OperationCancelledException(String.format(Locale.US, "Entity(%s): send operation failed. Please see cause for more details", entityPath), sendException, context) : new OperationCancelledException(String.format(Locale.US, "Entity(%s): send operation failed while advancing delivery(tag: %s).", entityPath, deliveryTag), context); workItem.error(exception, outcome); } } }
encodedBuffer.position(0);
private void processSendWork() { if (!hasConnected.get()) { logger.warning("Not connected. Not processing send work."); return; } if (isDisposed.get()) { logger.info("Sender is closed. Not executing work."); return; } while (hasConnected.get() && sender.getCredit() > 0) { final WeightedDeliveryTag weightedDelivery; final RetriableWorkItem workItem; final String deliveryTag; synchronized (pendingSendLock) { weightedDelivery = this.pendingSendsQueue.poll(); if (weightedDelivery != null) { deliveryTag = weightedDelivery.getDeliveryTag(); workItem = this.pendingSendsMap.get(deliveryTag); } else { workItem = null; deliveryTag = null; } } if (workItem == null) { if (deliveryTag != null) { logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .log("sendData not found for this delivery."); } break; } Delivery delivery = null; boolean linkAdvance = false; int sentMsgSize = 0; Exception sendException = null; try { workItem.beforeTry(); delivery = sender.delivery(deliveryTag.getBytes(UTF_8)); delivery.setMessageFormat(workItem.getMessageFormat()); if (workItem.isDeliveryStateProvided()) { delivery.disposition(workItem.getDeliveryState()); } workItem.send(sender); linkAdvance = sender.advance(); } catch (Exception exception) { sendException = exception; } if (linkAdvance) { logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .log("Sent message."); workItem.setWaitingForAck(); scheduler.schedule(new SendTimeout(deliveryTag), retryOptions.getTryTimeout().toMillis(), TimeUnit.MILLISECONDS); } else { logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .addKeyValue("sentMessageSize", sentMsgSize) .addKeyValue("payloadActualSize", workItem.getEncodedMessageSize()) .log("Sendlink advance failed."); DeliveryState outcome = null; if (delivery != null) { outcome = delivery.getRemoteState(); delivery.free(); } final AmqpErrorContext context = handler.getErrorContext(sender); final Throwable exception = sendException != null ? new OperationCancelledException(String.format(Locale.US, "Entity(%s): send operation failed. Please see cause for more details", entityPath), sendException, context) : new OperationCancelledException(String.format(Locale.US, "Entity(%s): send operation failed while advancing delivery(tag: %s).", entityPath, deliveryTag), context); workItem.error(exception, outcome); } } }
class ReactorSender implements AmqpSendLink, AsyncCloseable, AutoCloseable { private static final String DELIVERY_TAG_KEY = "deliveryTag"; private static final String PENDING_SENDS_SIZE_KEY = "pending_sends_size"; private final String entityPath; private final Sender sender; private final SendLinkHandler handler; private final ReactorProvider reactorProvider; private final Disposable.Composite subscriptions; private final AtomicBoolean hasConnected = new AtomicBoolean(); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger retryAttempts = new AtomicInteger(); private final Sinks.Empty<Void> isClosedMono = Sinks.empty(); private final Object pendingSendLock = new Object(); private final ConcurrentHashMap<String, RetriableWorkItem> pendingSendsMap = new ConcurrentHashMap<>(); private final PriorityQueue<WeightedDeliveryTag> pendingSendsQueue = new PriorityQueue<>(1000, new DeliveryTagComparator()); private final ClientLogger logger; private final Flux<AmqpEndpointState> endpointStates; private final TokenManager tokenManager; private final MessageSerializer messageSerializer; private final AmqpRetryPolicy retry; private final AmqpRetryOptions retryOptions; private final String activeTimeoutMessage; private final Scheduler scheduler; private final AmqpMetricsProvider metricsProvider; private final Object errorConditionLock = new Object(); private volatile Exception lastKnownLinkError; private volatile Instant lastKnownErrorReportedAt; private volatile int linkSize; /** * Creates an instance of {@link ReactorSender}. * * @param amqpConnection The parent {@link AmqpConnection} that this sender lives in. * @param entityPath The message broker address for the sender. * @param sender The underlying proton-j sender. * @param handler The proton-j handler associated with the sender. * @param reactorProvider Provider to schedule work on the proton-j reactor. * @param tokenManager Token manager for authorising with the CBS node. Can be {@code null} if it is part of the * transaction manager. * @param messageSerializer Serializer to deserialise and serialize AMQP messages. * @param retryOptions Retry options. * @param scheduler Scheduler to schedule send timeout. */ ReactorSender(AmqpConnection amqpConnection, String entityPath, Sender sender, SendLinkHandler handler, ReactorProvider reactorProvider, TokenManager tokenManager, MessageSerializer messageSerializer, AmqpRetryOptions retryOptions, Scheduler scheduler, AmqpMetricsProvider metricsProvider) { this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.sender = Objects.requireNonNull(sender, "'sender' cannot be null."); this.handler = Objects.requireNonNull(handler, "'handler' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.retry = RetryUtil.getRetryPolicy(retryOptions); this.tokenManager = tokenManager; this.metricsProvider = metricsProvider; String connectionId = handler.getConnectionId() == null ? NOT_APPLICABLE : handler.getConnectionId(); String linkName = getLinkName() == null ? NOT_APPLICABLE : getLinkName(); Map<String, Object> loggingContext = createContextWithConnectionId(connectionId); loggingContext.put(LINK_NAME_KEY, linkName); loggingContext.put(ENTITY_PATH_KEY, entityPath); this.logger = new ClientLogger(ReactorSender.class, loggingContext); this.activeTimeoutMessage = String.format( "ReactorSender connectionId[%s] linkName[%s]: Waiting for send and receive handler to be ACTIVE", handler.getConnectionId(), handler.getLinkName()); this.endpointStates = this.handler.getEndpointStates() .map(state -> { logger.verbose("State {}", state); this.hasConnected.set(state == EndpointState.ACTIVE); return AmqpEndpointStateUtil.getConnectionState(state); }) .doOnError(error -> { hasConnected.set(false); handleError(error); }) .doOnComplete(() -> { hasConnected.set(false); handleClose(); }) .cache(1); this.subscriptions = Disposables.composite( this.endpointStates.subscribe(), this.handler.getDeliveredMessages().subscribe(this::processDeliveredMessage), this.handler.getLinkCredits().subscribe(credit -> { logger.atVerbose().addKeyValue("credits", credit) .log("Credits on link."); this.scheduleWorkOnDispatcher(); }), amqpConnection.getShutdownSignals().flatMap(signal -> { logger.verbose("Shutdown signal received."); hasConnected.set(false); return closeAsync("Connection shutdown.", null); }).subscribe() ); if (tokenManager != null) { this.subscriptions.add(tokenManager.getAuthorizationResults().onErrorResume(error -> { final Mono<Void> operation = closeAsync(String.format("connectionId[%s] linkName[%s] Token renewal failure. Disposing send " + "link.", amqpConnection.getId(), getLinkName()), new ErrorCondition(Symbol.getSymbol(NOT_ALLOWED.getErrorCondition()), error.getMessage())); return operation.then(Mono.empty()); }).subscribe(response -> { logger.atVerbose().addKeyValue("response", response) .log("Token refreshed."); }, error -> { }, () -> { logger.verbose(" Authorization completed. Disposing."); closeAsync("Authorization completed. Disposing.", null).subscribe(); })); } } @Override public Flux<AmqpEndpointState> getEndpointStates() { return endpointStates; } @Override public Mono<Void> send(Message message) { return send(message, null); } @Override public Mono<Void> send(Message message, DeliveryState deliveryState) { if (isDisposed.get()) { return Mono.error(new IllegalStateException(String.format( "connectionId[%s] linkName[%s] Cannot publish message when disposed.", handler.getConnectionId(), getLinkName()))); } return getLinkSize() .flatMap(maxMessageSize -> { final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); final Throwable error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, handler.getErrorContext(sender)); return Mono.error(error); } return send(bytes, encodedSize, DeliveryImpl.DEFAULT_MESSAGE_FORMAT, deliveryState); }).then(); } @Override public Mono<Void> send(List<Message> messageBatch) { return send(messageBatch, null); } @Override public Mono<Void> send(List<Message> messageBatch, DeliveryState deliveryState) { if (isDisposed.get()) { return Mono.error(new IllegalStateException(String.format( "connectionId[%s] linkName[%s] Cannot publish data batch when disposed.", handler.getConnectionId(), getLinkName()))); } if (messageBatch.size() == 1) { return send(messageBatch.get(0), deliveryState); } return getLinkSize() .flatMap(maxMessageSize -> { final Message firstMessage = messageBatch.get(0); final Message batchMessage = Proton.message(); batchMessage.setMessageAnnotations(firstMessage.getMessageAnnotations()); final int maxMessageSizeTemp = maxMessageSize; final byte[] bytes = new byte[maxMessageSizeTemp]; int encodedSize = batchMessage.encode(bytes, 0, maxMessageSizeTemp); int byteArrayOffset = encodedSize; for (final Message amqpMessage : messageBatch) { final Message messageWrappedByData = Proton.message(); int payloadSize = messageSerializer.getSize(amqpMessage); int allocationSize = Math.min(payloadSize + MAX_AMQP_HEADER_SIZE_BYTES, maxMessageSizeTemp); byte[] messageBytes = new byte[allocationSize]; int messageSizeBytes = amqpMessage.encode(messageBytes, 0, allocationSize); messageWrappedByData.setBody(new Data(new Binary(messageBytes, 0, messageSizeBytes))); try { encodedSize = messageWrappedByData .encode(bytes, byteArrayOffset, maxMessageSizeTemp - byteArrayOffset - 1); } catch (BufferOverflowException exception) { final String message = String.format(Locale.US, "Size of the payload exceeded maximum message size: %s kb", maxMessageSizeTemp / 1024); final AmqpException error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, exception, handler.getErrorContext(sender)); return Mono.error(error); } byteArrayOffset = byteArrayOffset + encodedSize; } return send(bytes, byteArrayOffset, AmqpConstants.AMQP_BATCH_MESSAGE_FORMAT, deliveryState); }).then(); } private Mono<Void> batchSend(List<Message> batch, int maxMessageSize, DeliveryState deliveryState) { int totalEncodedSize = 0; final CompositeReadableBuffer buffer = new CompositeReadableBuffer(); final byte[] envelopBytes = batchEnvelopAsBinaryData(batch.get(0), maxMessageSize); totalEncodedSize += envelopBytes.length; if (totalEncodedSize > maxMessageSize) { return batchBufferOverflowError(maxMessageSize); } buffer.append(envelopBytes); for (final Message message : batch) { final byte[] sectionBytes = batchSectionAsBinaryData(message, maxMessageSize); totalEncodedSize += sectionBytes.length; if (totalEncodedSize > maxMessageSize) { return batchBufferOverflowError(maxMessageSize); } buffer.append(sectionBytes); } final Flux<EndpointState> activeEndpointFlux = RetryUtil.withRetry( handler.getEndpointStates().takeUntil(state -> state == EndpointState.ACTIVE), retryOptions, activeTimeoutMessage); final int totalEncodedBufferSize = totalEncodedSize; Mono<DeliveryState> sendMono = activeEndpointFlux.then(Mono.create(sink -> { sendWork(new RetriableWorkItem(buffer, totalEncodedBufferSize, AmqpConstants.AMQP_BATCH_MESSAGE_FORMAT, sink, retryOptions.getTryTimeout(), deliveryState, metricsProvider)); })); return sendMono.then(); } private byte[] batchEnvelopAsBinaryData(Message envelopMessage, int maxMessageSize) { final Message message = Proton.message(); message.setMessageAnnotations(envelopMessage.getMessageAnnotations()); final int size = messageSerializer.getSize(message); final int allocationSize = Math.min(size + MAX_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] encodedBytes = new byte[allocationSize]; final int encodedSize = message.encode(encodedBytes, 0, allocationSize); return Arrays.copyOf(encodedBytes, encodedSize); } private byte[] batchSectionAsBinaryData(Message sectionMessage, int maxMessageSize) { final int size = messageSerializer.getSize(sectionMessage); final int allocationSize = Math.min(size + MAX_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] encodedBytes = new byte[allocationSize]; final int encodedSize = sectionMessage.encode(encodedBytes, 0, allocationSize); final Message message = Proton.message(); final Data binaryData = new Data(new Binary(encodedBytes, 0, encodedSize)); message.setBody(binaryData); final int binaryRawSize = binaryData.getValue().getLength(); final int binaryEncodedSize = binaryEncodedSize(binaryRawSize); final byte[] binaryEncodedBytes = new byte[binaryEncodedSize]; message.encode(binaryEncodedBytes, 0, binaryEncodedSize); return binaryEncodedBytes; } private Mono<Void> batchBufferOverflowError(int maxMessageSize) { return Mono.error(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, String.format(Locale.US, "Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024), new BufferOverflowException(), handler.getErrorContext(sender))); } private int binaryEncodedSize(int binaryRawSize) { if (binaryRawSize <= 255) { return 5 + binaryRawSize; } else { return 8 + binaryRawSize; } } @Override public AmqpErrorContext getErrorContext() { return handler.getErrorContext(sender); } @Override public String getLinkName() { return sender.getName(); } @Override public String getEntityPath() { return entityPath; } @Override public String getHostname() { return handler.getHostname(); } @Override public Mono<Integer> getLinkSize() { if (linkSize > 0) { return Mono.defer(() -> Mono.just(this.linkSize)); } synchronized (this) { if (linkSize > 0) { return Mono.defer(() -> Mono.just(linkSize)); } return RetryUtil.withRetry(getEndpointStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE), retryOptions, activeTimeoutMessage) .then(Mono.fromCallable(() -> { final UnsignedLong remoteMaxMessageSize = sender.getRemoteMaxMessageSize(); if (remoteMaxMessageSize != null) { linkSize = remoteMaxMessageSize.intValue(); } else { logger.warning("Could not get the getRemoteMaxMessageSize. Returning current link size: {}", linkSize); } return linkSize; })); } } @Override public boolean isDisposed() { return isDisposed.get(); } /** * Blocking call that disposes of the sender. * * @see */ @Override public void dispose() { close(); } /** * Blocking call that disposes of the sender. * * @see */ @Override public void close() { closeAsync().block(retryOptions.getTryTimeout()); } @Override public Mono<Void> closeAsync() { return closeAsync("User invoked close operation.", null); } /** * Disposes of the sender. * * @param errorCondition Error condition associated with close operation. * @param message Message associated with why the sender was closed. * * @return A mono that completes when the send link has closed. */ Mono<Void> closeAsync(String message, ErrorCondition errorCondition) { if (isDisposed.getAndSet(true)) { return isClosedMono.asMono(); } addErrorCondition(logger.atVerbose(), errorCondition) .log("Setting error condition and disposing. {}", message); final Runnable closeWork = () -> { if (errorCondition != null && sender.getCondition() == null) { sender.setCondition(errorCondition); } sender.close(); }; return Mono.fromRunnable(() -> { try { reactorProvider.getReactorDispatcher().invoke(closeWork); } catch (IOException e) { logger.warning("Could not schedule close work. Running manually. And completing close.", e); closeWork.run(); handleClose(); } catch (RejectedExecutionException e) { logger.info("RejectedExecutionException scheduling close work. And completing close."); closeWork.run(); handleClose(); } }).then(isClosedMono.asMono()) .publishOn(Schedulers.boundedElastic()); } /** * A mono that completes when the sender has completely closed. * * @return mono that completes when the sender has completely closed. */ Mono<Void> isClosed() { return isClosedMono.asMono(); } @Override public Mono<DeliveryState> send(byte[] bytes, int arrayOffset, int messageFormat, DeliveryState deliveryState) { final Flux<EndpointState> activeEndpointFlux = RetryUtil.withRetry( handler.getEndpointStates().takeUntil(state -> state == EndpointState.ACTIVE), retryOptions, activeTimeoutMessage); return activeEndpointFlux.then(Mono.create(sink -> { sendWork(new RetriableWorkItem(bytes, arrayOffset, messageFormat, sink, retryOptions.getTryTimeout(), deliveryState, metricsProvider)); })); } /** * Add the work item in pending send to be processed on {@link ReactorDispatcher} thread. * * @param workItem to be processed. */ private void sendWork(RetriableWorkItem workItem) { final String deliveryTag = UUID.randomUUID().toString().replace("-", ""); synchronized (pendingSendLock) { this.pendingSendsMap.put(deliveryTag, workItem); this.pendingSendsQueue.offer(new WeightedDeliveryTag(deliveryTag, workItem.hasBeenRetried() ? 1 : 0)); } this.scheduleWorkOnDispatcher(); } /** * Invokes work on the Reactor. Should only be called from ReactorDispatcher.invoke() */ private void processDeliveredMessage(Delivery delivery) { final DeliveryState outcome = delivery.getRemoteState(); final String deliveryTag = new String(delivery.getTag(), UTF_8); logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .log("Process delivered message."); final RetriableWorkItem workItem = pendingSendsMap.remove(deliveryTag); if (workItem == null) { logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .log("Mismatch (or send timed out)."); return; } else if (workItem.isDeliveryStateProvided()) { workItem.success(outcome); return; } if (outcome instanceof Accepted) { synchronized (errorConditionLock) { lastKnownLinkError = null; lastKnownErrorReportedAt = null; retryAttempts.set(0); } workItem.success(outcome); } else if (outcome instanceof Rejected) { final Rejected rejected = (Rejected) outcome; final org.apache.qpid.proton.amqp.transport.ErrorCondition error = rejected.getError(); final Exception exception = ExceptionUtil.toException(error.getCondition().toString(), error.getDescription(), handler.getErrorContext(sender)); logger.atWarning() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .addKeyValue("rejected", rejected) .log("Delivery rejected."); final int retryAttempt; if (isGeneralSendError(error.getCondition())) { synchronized (errorConditionLock) { lastKnownLinkError = exception; lastKnownErrorReportedAt = Instant.now(); retryAttempt = retryAttempts.incrementAndGet(); } } else { retryAttempt = retryAttempts.get(); } final Duration retryInterval = retry.calculateRetryDelay(exception, retryAttempt); if (retryInterval == null || retryInterval.compareTo(workItem.getTimeoutTracker().remaining()) > 0) { cleanupFailedSend(workItem, exception, outcome); } else { workItem.setLastKnownException(exception); try { reactorProvider.getReactorDispatcher().invoke(() -> sendWork(workItem), retryInterval); } catch (IOException | RejectedExecutionException schedulerException) { exception.initCause(schedulerException); cleanupFailedSend( workItem, new AmqpException(false, String.format(Locale.US, "Entity(%s): send operation failed while scheduling a" + " retry on Reactor, see cause for more details.", entityPath), schedulerException, handler.getErrorContext(sender)), outcome); } } } else if (outcome instanceof Released) { cleanupFailedSend(workItem, new OperationCancelledException(outcome.toString(), handler.getErrorContext(sender)), outcome); } else if (outcome instanceof Declared) { final Declared declared = (Declared) outcome; workItem.success(declared); } else { cleanupFailedSend(workItem, new AmqpException(false, outcome.toString(), handler.getErrorContext(sender)), outcome); } } private void scheduleWorkOnDispatcher() { try { reactorProvider.getReactorDispatcher().invoke(this::processSendWork); } catch (IOException e) { logger.warning("Error scheduling work on reactor.", e); } catch (RejectedExecutionException e) { logger.info("Error scheduling work on reactor because of RejectedExecutionException."); } } private void cleanupFailedSend(final RetriableWorkItem workItem, final Exception exception, final DeliveryState deliveryState) { workItem.error(exception, deliveryState); } private void completeClose() { isClosedMono.emitEmpty((signalType, result) -> { addSignalTypeAndResult(logger.atWarning(), signalType, result).log("Unable to emit shutdown signal."); return false; }); subscriptions.dispose(); if (tokenManager != null) { tokenManager.close(); } } /** * Clears pending sends and puts an error in there. * * @param error Error to pass to pending sends. */ private void handleError(Throwable error) { synchronized (pendingSendLock) { if (isDisposed.getAndSet(true)) { logger.verbose("This was already disposed. Dropping error."); } else { logger.atVerbose() .addKeyValue(PENDING_SENDS_SIZE_KEY, () -> String.valueOf(pendingSendsMap.size())) .log("Disposing pending sends with error."); } pendingSendsMap.forEach((key, value) -> value.error(error, null)); pendingSendsMap.clear(); pendingSendsQueue.clear(); } completeClose(); } private void handleClose() { final String message = String.format("Could not complete sends because link '%s' for '%s' is closed.", getLinkName(), entityPath); final AmqpErrorContext context = handler.getErrorContext(sender); synchronized (pendingSendLock) { if (isDisposed.getAndSet(true)) { logger.verbose("This was already disposed."); } else { logger.atVerbose() .addKeyValue(PENDING_SENDS_SIZE_KEY, () -> String.valueOf(pendingSendsMap.size())) .log("Disposing pending sends."); } pendingSendsMap.forEach((key, value) -> value.error(new AmqpException(true, message, context), null)); pendingSendsMap.clear(); pendingSendsQueue.clear(); } completeClose(); } private static boolean isGeneralSendError(Symbol amqpError) { return (amqpError == AmqpErrorCode.SERVER_BUSY_ERROR || amqpError == AmqpErrorCode.TIMEOUT_ERROR || amqpError == AmqpErrorCode.RESOURCE_LIMIT_EXCEEDED); } private static class WeightedDeliveryTag { private final String deliveryTag; private final int priority; WeightedDeliveryTag(final String deliveryTag, final int priority) { this.deliveryTag = deliveryTag; this.priority = priority; } private String getDeliveryTag() { return this.deliveryTag; } private int getPriority() { return this.priority; } } private static class DeliveryTagComparator implements Comparator<WeightedDeliveryTag>, Serializable { private static final long serialVersionUID = -7057500582037295635L; @Override public int compare(WeightedDeliveryTag deliveryTag0, WeightedDeliveryTag deliveryTag1) { return deliveryTag1.getPriority() - deliveryTag0.getPriority(); } } /** * Keeps track of messages that have been sent, but may not have been acknowledged by the service. */ private class SendTimeout implements Runnable { private final String deliveryTag; SendTimeout(String deliveryTag) { this.deliveryTag = deliveryTag; } @Override public void run() { final RetriableWorkItem workItem = pendingSendsMap.remove(deliveryTag); if (workItem == null) { return; } Exception cause = lastKnownLinkError; final Exception lastError; final Instant lastErrorTime; synchronized (errorConditionLock) { lastError = lastKnownLinkError; lastErrorTime = lastKnownErrorReportedAt; } if (lastError != null && lastErrorTime != null) { final Instant now = Instant.now(); final boolean isLastErrorAfterSleepTime = lastErrorTime.isAfter(now.minusSeconds(SERVER_BUSY_BASE_SLEEP_TIME_IN_SECS)); final boolean isServerBusy = lastError instanceof AmqpException && isLastErrorAfterSleepTime; final boolean isLastErrorAfterOperationTimeout = lastErrorTime.isAfter(now.minus(retryOptions.getTryTimeout())); cause = isServerBusy || isLastErrorAfterOperationTimeout ? lastError : null; } final AmqpException exception; if (cause instanceof AmqpException) { exception = (AmqpException) cause; } else { exception = new AmqpException(true, AmqpErrorCondition.TIMEOUT_ERROR, String.format(Locale.US, "Entity(%s): Send operation timed out", entityPath), handler.getErrorContext(sender)); } workItem.error(exception, null); } } }
class ReactorSender implements AmqpSendLink, AsyncCloseable, AutoCloseable { private static final String DELIVERY_TAG_KEY = "deliveryTag"; private static final String PENDING_SENDS_SIZE_KEY = "pending_sends_size"; private final String entityPath; private final Sender sender; private final SendLinkHandler handler; private final ReactorProvider reactorProvider; private final Disposable.Composite subscriptions; private final AtomicBoolean hasConnected = new AtomicBoolean(); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicInteger retryAttempts = new AtomicInteger(); private final Sinks.Empty<Void> isClosedMono = Sinks.empty(); private final Object pendingSendLock = new Object(); private final ConcurrentHashMap<String, RetriableWorkItem> pendingSendsMap = new ConcurrentHashMap<>(); private final PriorityQueue<WeightedDeliveryTag> pendingSendsQueue = new PriorityQueue<>(1000, new DeliveryTagComparator()); private final ClientLogger logger; private final Flux<AmqpEndpointState> endpointStates; private final TokenManager tokenManager; private final MessageSerializer messageSerializer; private final AmqpRetryPolicy retry; private final AmqpRetryOptions retryOptions; private final String activeTimeoutMessage; private final Scheduler scheduler; private final AmqpMetricsProvider metricsProvider; private final Object errorConditionLock = new Object(); private volatile Exception lastKnownLinkError; private volatile Instant lastKnownErrorReportedAt; private volatile int linkSize; /** * Creates an instance of {@link ReactorSender}. * * @param amqpConnection The parent {@link AmqpConnection} that this sender lives in. * @param entityPath The message broker address for the sender. * @param sender The underlying proton-j sender. * @param handler The proton-j handler associated with the sender. * @param reactorProvider Provider to schedule work on the proton-j reactor. * @param tokenManager Token manager for authorising with the CBS node. Can be {@code null} if it is part of the * transaction manager. * @param messageSerializer Serializer to deserialise and serialize AMQP messages. * @param retryOptions Retry options. * @param scheduler Scheduler to schedule send timeout. */ ReactorSender(AmqpConnection amqpConnection, String entityPath, Sender sender, SendLinkHandler handler, ReactorProvider reactorProvider, TokenManager tokenManager, MessageSerializer messageSerializer, AmqpRetryOptions retryOptions, Scheduler scheduler, AmqpMetricsProvider metricsProvider) { this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.sender = Objects.requireNonNull(sender, "'sender' cannot be null."); this.handler = Objects.requireNonNull(handler, "'handler' cannot be null."); this.reactorProvider = Objects.requireNonNull(reactorProvider, "'reactorProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.retry = RetryUtil.getRetryPolicy(retryOptions); this.tokenManager = tokenManager; this.metricsProvider = metricsProvider; String connectionId = handler.getConnectionId() == null ? NOT_APPLICABLE : handler.getConnectionId(); String linkName = getLinkName() == null ? NOT_APPLICABLE : getLinkName(); Map<String, Object> loggingContext = createContextWithConnectionId(connectionId); loggingContext.put(LINK_NAME_KEY, linkName); loggingContext.put(ENTITY_PATH_KEY, entityPath); this.logger = new ClientLogger(ReactorSender.class, loggingContext); this.activeTimeoutMessage = String.format( "ReactorSender connectionId[%s] linkName[%s]: Waiting for send and receive handler to be ACTIVE", handler.getConnectionId(), handler.getLinkName()); this.endpointStates = this.handler.getEndpointStates() .map(state -> { logger.verbose("State {}", state); this.hasConnected.set(state == EndpointState.ACTIVE); return AmqpEndpointStateUtil.getConnectionState(state); }) .doOnError(error -> { hasConnected.set(false); handleError(error); }) .doOnComplete(() -> { hasConnected.set(false); handleClose(); }) .cache(1); this.subscriptions = Disposables.composite( this.endpointStates.subscribe(), this.handler.getDeliveredMessages().subscribe(this::processDeliveredMessage), this.handler.getLinkCredits().subscribe(credit -> { logger.atVerbose().addKeyValue("credits", credit) .log("Credits on link."); this.scheduleWorkOnDispatcher(); }), amqpConnection.getShutdownSignals().flatMap(signal -> { logger.verbose("Shutdown signal received."); hasConnected.set(false); return closeAsync("Connection shutdown.", null); }).subscribe() ); if (tokenManager != null) { this.subscriptions.add(tokenManager.getAuthorizationResults().onErrorResume(error -> { final Mono<Void> operation = closeAsync(String.format("connectionId[%s] linkName[%s] Token renewal failure. Disposing send " + "link.", amqpConnection.getId(), getLinkName()), new ErrorCondition(Symbol.getSymbol(NOT_ALLOWED.getErrorCondition()), error.getMessage())); return operation.then(Mono.empty()); }).subscribe(response -> { logger.atVerbose().addKeyValue("response", response) .log("Token refreshed."); }, error -> { }, () -> { logger.verbose(" Authorization completed. Disposing."); closeAsync("Authorization completed. Disposing.", null).subscribe(); })); } } @Override public Flux<AmqpEndpointState> getEndpointStates() { return endpointStates; } @Override public Mono<Void> send(Message message) { return send(message, null); } @Override public Mono<Void> send(Message message, DeliveryState deliveryState) { if (isDisposed.get()) { return Mono.error(new IllegalStateException(String.format( "connectionId[%s] linkName[%s] Cannot publish message when disposed.", handler.getConnectionId(), getLinkName()))); } return getLinkSize() .flatMap(maxMessageSize -> { final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); final Throwable error = new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, handler.getErrorContext(sender)); return Mono.error(error); } return send(bytes, encodedSize, DeliveryImpl.DEFAULT_MESSAGE_FORMAT, deliveryState); }).then(); } @Override public Mono<Void> send(List<Message> messageBatch) { return send(messageBatch, null); } @Override public Mono<Void> send(List<Message> messageBatch, DeliveryState deliveryState) { if (isDisposed.get()) { return Mono.error(new IllegalStateException(String.format( "connectionId[%s] linkName[%s] Cannot publish data batch when disposed.", handler.getConnectionId(), getLinkName()))); } if (messageBatch.size() == 1) { return send(messageBatch.get(0), deliveryState); } return getLinkSize() .flatMap(maxMessageSize -> { int totalEncodedSize = 0; final CompositeReadableBuffer buffer = new CompositeReadableBuffer(); final byte[] envelopBytes = batchEnvelopBytes(messageBatch.get(0), maxMessageSize); if (envelopBytes.length > 0) { totalEncodedSize += envelopBytes.length; if (totalEncodedSize > maxMessageSize) { return batchBufferOverflowError(maxMessageSize); } buffer.append(envelopBytes); } for (final Message message : messageBatch) { final byte[] sectionBytes = batchBinaryDataSectionBytes(message, maxMessageSize); if (sectionBytes.length > 0) { totalEncodedSize += sectionBytes.length; if (totalEncodedSize > maxMessageSize) { return batchBufferOverflowError(maxMessageSize); } buffer.append(sectionBytes); } else { logger.info("Ignoring the empty message org.apache.qpid.proton.message.message@{} in the batch.", Integer.toHexString(System.identityHashCode(message))); } } return send(buffer, AmqpConstants.AMQP_BATCH_MESSAGE_FORMAT, deliveryState); }).then(); } private byte[] batchEnvelopBytes(Message envelopMessage, int maxMessageSize) { final Message message = Proton.message(); message.setMessageAnnotations(envelopMessage.getMessageAnnotations()); if ((envelopMessage.getMessageId() instanceof String) && !CoreUtils.isNullOrEmpty((String) envelopMessage.getMessageId())) { message.setMessageId(envelopMessage.getMessageId()); } if (!CoreUtils.isNullOrEmpty(envelopMessage.getGroupId())) { message.setGroupId(envelopMessage.getGroupId()); } final int size = messageSerializer.getSize(message); final int allocationSize = Math.min(size + MAX_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] encodedBytes = new byte[allocationSize]; final int encodedSize = message.encode(encodedBytes, 0, allocationSize); return Arrays.copyOf(encodedBytes, encodedSize); } private byte[] batchBinaryDataSectionBytes(Message sectionMessage, int maxMessageSize) { final int size = messageSerializer.getSize(sectionMessage); final int allocationSize = Math.min(size + MAX_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] encodedBytes = new byte[allocationSize]; final int encodedSize = sectionMessage.encode(encodedBytes, 0, allocationSize); final Message message = Proton.message(); final Data binaryData = new Data(new Binary(encodedBytes, 0, encodedSize)); message.setBody(binaryData); final int binaryRawSize = binaryData.getValue().getLength(); final int binaryEncodedSize = binaryEncodedSize(binaryRawSize); final byte[] binaryEncodedBytes = new byte[binaryEncodedSize]; message.encode(binaryEncodedBytes, 0, binaryEncodedSize); return binaryEncodedBytes; } private Mono<Void> batchBufferOverflowError(int maxMessageSize) { return FluxUtil.monoError(logger, new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, String.format(Locale.US, "Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024), new BufferOverflowException(), handler.getErrorContext(sender))); } /** * Compute the encoded size when encoding a binary data of given size per Amqp 1.0 spec "amqp:data:binary" format. * * @param binaryRawSize the length of the binary data. * @return the encoded size. */ private int binaryEncodedSize(int binaryRawSize) { if (binaryRawSize <= 255) { return 5 + binaryRawSize; } else { return 8 + binaryRawSize; } } @Override public AmqpErrorContext getErrorContext() { return handler.getErrorContext(sender); } @Override public String getLinkName() { return sender.getName(); } @Override public String getEntityPath() { return entityPath; } @Override public String getHostname() { return handler.getHostname(); } @Override public Mono<Integer> getLinkSize() { if (linkSize > 0) { return Mono.defer(() -> Mono.just(this.linkSize)); } synchronized (this) { if (linkSize > 0) { return Mono.defer(() -> Mono.just(linkSize)); } return RetryUtil.withRetry(getEndpointStates().takeUntil(state -> state == AmqpEndpointState.ACTIVE), retryOptions, activeTimeoutMessage) .then(Mono.fromCallable(() -> { final UnsignedLong remoteMaxMessageSize = sender.getRemoteMaxMessageSize(); if (remoteMaxMessageSize != null) { linkSize = remoteMaxMessageSize.intValue(); } else { logger.warning("Could not get the getRemoteMaxMessageSize. Returning current link size: {}", linkSize); } return linkSize; })); } } @Override public boolean isDisposed() { return isDisposed.get(); } /** * Blocking call that disposes of the sender. * * @see */ @Override public void dispose() { close(); } /** * Blocking call that disposes of the sender. * * @see */ @Override public void close() { closeAsync().block(retryOptions.getTryTimeout()); } @Override public Mono<Void> closeAsync() { return closeAsync("User invoked close operation.", null); } /** * Disposes of the sender. * * @param errorCondition Error condition associated with close operation. * @param message Message associated with why the sender was closed. * * @return A mono that completes when the send link has closed. */ Mono<Void> closeAsync(String message, ErrorCondition errorCondition) { if (isDisposed.getAndSet(true)) { return isClosedMono.asMono(); } addErrorCondition(logger.atVerbose(), errorCondition) .log("Setting error condition and disposing. {}", message); final Runnable closeWork = () -> { if (errorCondition != null && sender.getCondition() == null) { sender.setCondition(errorCondition); } sender.close(); }; return Mono.fromRunnable(() -> { try { reactorProvider.getReactorDispatcher().invoke(closeWork); } catch (IOException e) { logger.warning("Could not schedule close work. Running manually. And completing close.", e); closeWork.run(); handleClose(); } catch (RejectedExecutionException e) { logger.info("RejectedExecutionException scheduling close work. And completing close."); closeWork.run(); handleClose(); } }).then(isClosedMono.asMono()) .publishOn(Schedulers.boundedElastic()); } /** * A mono that completes when the sender has completely closed. * * @return mono that completes when the sender has completely closed. */ Mono<Void> isClosed() { return isClosedMono.asMono(); } @Override public Mono<DeliveryState> send(byte[] bytes, int arrayOffset, int messageFormat, DeliveryState deliveryState) { return onEndpointActive().then(Mono.create(sink -> { sendWork(new RetriableWorkItem(bytes, arrayOffset, messageFormat, sink, retryOptions.getTryTimeout(), deliveryState, metricsProvider)); })); } Mono<DeliveryState> send(ReadableBuffer buffer, int messageFormat, DeliveryState deliveryState) { return onEndpointActive().then(Mono.create(sink -> { sendWork(new RetriableWorkItem(buffer, messageFormat, sink, retryOptions.getTryTimeout(), deliveryState, metricsProvider)); })); } private Flux<EndpointState> onEndpointActive() { return RetryUtil.withRetry(handler.getEndpointStates().takeUntil(state -> state == EndpointState.ACTIVE), retryOptions, activeTimeoutMessage); } /** * Add the work item in pending send to be processed on {@link ReactorDispatcher} thread. * * @param workItem to be processed. */ private void sendWork(RetriableWorkItem workItem) { final String deliveryTag = UUID.randomUUID().toString().replace("-", ""); synchronized (pendingSendLock) { this.pendingSendsMap.put(deliveryTag, workItem); this.pendingSendsQueue.offer(new WeightedDeliveryTag(deliveryTag, workItem.hasBeenRetried() ? 1 : 0)); } this.scheduleWorkOnDispatcher(); } /** * Invokes work on the Reactor. Should only be called from ReactorDispatcher.invoke() */ private void processDeliveredMessage(Delivery delivery) { final DeliveryState outcome = delivery.getRemoteState(); final String deliveryTag = new String(delivery.getTag(), UTF_8); logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .log("Process delivered message."); final RetriableWorkItem workItem = pendingSendsMap.remove(deliveryTag); if (workItem == null) { logger.atVerbose() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .log("Mismatch (or send timed out)."); return; } else if (workItem.isDeliveryStateProvided()) { workItem.success(outcome); return; } if (outcome instanceof Accepted) { synchronized (errorConditionLock) { lastKnownLinkError = null; lastKnownErrorReportedAt = null; retryAttempts.set(0); } workItem.success(outcome); } else if (outcome instanceof Rejected) { final Rejected rejected = (Rejected) outcome; final org.apache.qpid.proton.amqp.transport.ErrorCondition error = rejected.getError(); final Exception exception = ExceptionUtil.toException(error.getCondition().toString(), error.getDescription(), handler.getErrorContext(sender)); logger.atWarning() .addKeyValue(DELIVERY_TAG_KEY, deliveryTag) .addKeyValue("rejected", rejected) .log("Delivery rejected."); final int retryAttempt; if (isGeneralSendError(error.getCondition())) { synchronized (errorConditionLock) { lastKnownLinkError = exception; lastKnownErrorReportedAt = Instant.now(); retryAttempt = retryAttempts.incrementAndGet(); } } else { retryAttempt = retryAttempts.get(); } final Duration retryInterval = retry.calculateRetryDelay(exception, retryAttempt); if (retryInterval == null || retryInterval.compareTo(workItem.getTimeoutTracker().remaining()) > 0) { cleanupFailedSend(workItem, exception, outcome); } else { workItem.setLastKnownException(exception); try { reactorProvider.getReactorDispatcher().invoke(() -> sendWork(workItem), retryInterval); } catch (IOException | RejectedExecutionException schedulerException) { exception.initCause(schedulerException); cleanupFailedSend( workItem, new AmqpException(false, String.format(Locale.US, "Entity(%s): send operation failed while scheduling a" + " retry on Reactor, see cause for more details.", entityPath), schedulerException, handler.getErrorContext(sender)), outcome); } } } else if (outcome instanceof Released) { cleanupFailedSend(workItem, new OperationCancelledException(outcome.toString(), handler.getErrorContext(sender)), outcome); } else if (outcome instanceof Declared) { final Declared declared = (Declared) outcome; workItem.success(declared); } else { cleanupFailedSend(workItem, new AmqpException(false, outcome.toString(), handler.getErrorContext(sender)), outcome); } } private void scheduleWorkOnDispatcher() { try { reactorProvider.getReactorDispatcher().invoke(this::processSendWork); } catch (IOException e) { logger.warning("Error scheduling work on reactor.", e); } catch (RejectedExecutionException e) { logger.info("Error scheduling work on reactor because of RejectedExecutionException."); } } private void cleanupFailedSend(final RetriableWorkItem workItem, final Exception exception, final DeliveryState deliveryState) { workItem.error(exception, deliveryState); } private void completeClose() { isClosedMono.emitEmpty((signalType, result) -> { addSignalTypeAndResult(logger.atWarning(), signalType, result).log("Unable to emit shutdown signal."); return false; }); subscriptions.dispose(); if (tokenManager != null) { tokenManager.close(); } } /** * Clears pending sends and puts an error in there. * * @param error Error to pass to pending sends. */ private void handleError(Throwable error) { synchronized (pendingSendLock) { if (isDisposed.getAndSet(true)) { logger.verbose("This was already disposed. Dropping error."); } else { logger.atVerbose() .addKeyValue(PENDING_SENDS_SIZE_KEY, () -> String.valueOf(pendingSendsMap.size())) .log("Disposing pending sends with error."); } pendingSendsMap.forEach((key, value) -> value.error(error, null)); pendingSendsMap.clear(); pendingSendsQueue.clear(); } completeClose(); } private void handleClose() { final String message = String.format("Could not complete sends because link '%s' for '%s' is closed.", getLinkName(), entityPath); final AmqpErrorContext context = handler.getErrorContext(sender); synchronized (pendingSendLock) { if (isDisposed.getAndSet(true)) { logger.verbose("This was already disposed."); } else { logger.atVerbose() .addKeyValue(PENDING_SENDS_SIZE_KEY, () -> String.valueOf(pendingSendsMap.size())) .log("Disposing pending sends."); } pendingSendsMap.forEach((key, value) -> value.error(new AmqpException(true, message, context), null)); pendingSendsMap.clear(); pendingSendsQueue.clear(); } completeClose(); } private static boolean isGeneralSendError(Symbol amqpError) { return (amqpError == AmqpErrorCode.SERVER_BUSY_ERROR || amqpError == AmqpErrorCode.TIMEOUT_ERROR || amqpError == AmqpErrorCode.RESOURCE_LIMIT_EXCEEDED); } private static class WeightedDeliveryTag { private final String deliveryTag; private final int priority; WeightedDeliveryTag(final String deliveryTag, final int priority) { this.deliveryTag = deliveryTag; this.priority = priority; } private String getDeliveryTag() { return this.deliveryTag; } private int getPriority() { return this.priority; } } private static class DeliveryTagComparator implements Comparator<WeightedDeliveryTag>, Serializable { private static final long serialVersionUID = -7057500582037295635L; @Override public int compare(WeightedDeliveryTag deliveryTag0, WeightedDeliveryTag deliveryTag1) { return deliveryTag1.getPriority() - deliveryTag0.getPriority(); } } /** * Keeps track of messages that have been sent, but may not have been acknowledged by the service. */ private class SendTimeout implements Runnable { private final String deliveryTag; SendTimeout(String deliveryTag) { this.deliveryTag = deliveryTag; } @Override public void run() { final RetriableWorkItem workItem = pendingSendsMap.remove(deliveryTag); if (workItem == null) { return; } Exception cause = lastKnownLinkError; final Exception lastError; final Instant lastErrorTime; synchronized (errorConditionLock) { lastError = lastKnownLinkError; lastErrorTime = lastKnownErrorReportedAt; } if (lastError != null && lastErrorTime != null) { final Instant now = Instant.now(); final boolean isLastErrorAfterSleepTime = lastErrorTime.isAfter(now.minusSeconds(SERVER_BUSY_BASE_SLEEP_TIME_IN_SECS)); final boolean isServerBusy = lastError instanceof AmqpException && isLastErrorAfterSleepTime; final boolean isLastErrorAfterOperationTimeout = lastErrorTime.isAfter(now.minus(retryOptions.getTryTimeout())); cause = isServerBusy || isLastErrorAfterOperationTimeout ? lastError : null; } final AmqpException exception; if (cause instanceof AmqpException) { exception = (AmqpException) cause; } else { exception = new AmqpException(true, AmqpErrorCondition.TIMEOUT_ERROR, String.format(Locale.US, "Entity(%s): Send operation timed out", entityPath), handler.getErrorContext(sender)); } workItem.error(exception, null); } } }